gpt4 book ai didi

ruby-on-rails - Ruby on Rails : Polymorphic Association with Nested Attributes, 字段未显示

转载 作者:数据小太阳 更新时间:2023-10-29 08:12:24 25 4
gpt4 key购买 nike

我有一个多态关联表单,我想构建一个嵌套表单,但字段没有显示:

views/reviews/_form.html.erb:

<%= form_for [@reviewable, @review] do |f| %>
<%= f.fields_for :review_images do |i| %>
<%= i.file_field :image %>
<% end %>
<% end %>

review.rb:

class Review < ActiveRecord::Base
attr_accessible :review_styles_attributes
belongs_to :reviewable, polymorphic: true
has_many :review_styles
accepts_nested_attributes_for :review_images, allow_destroy: true
end

review_image.rb:

class ReviewStyle < ActiveRecord::Base
attr_accessible :review_id, :image
belongs_to :reviewable, polymorphic: true
belongs_to :review
end

reviews_controller.rb:

class ReviewsController < ApplicationController
before_filter :get_reviewable

def new
@review = @reviewable.reviews.new
@review_style = @review.build_review_style
3.times {@review.review_styles.new}
end

def edit
# not sure what goes here if I need to edit as well
end

private
def get_reviewable
@reviewable = params[:reviewable].classify.constantize.find(reviewable_id)
end

def reviewable_id
params[(params[:reviewable].singularize + "_id").to_sym]
end
end

最佳答案

我认为你的问题出在这里:

  <%= f.fields_for :review_images do |i| %>
<%= i.file_field :image %>
<% end %>

从你的代码来看,它应该是:

  #app/views/reviews/new.html.erb
<%= f.fields_for :review_styles do |i| %>
<%= i.file_field :image %>
<% end %>

#app/controllers/reviews_controller.rb
def new
@review = @reviewable.reviews.new
@review.review_styles.build
end

你应该注意,当你构建关联值时,你应该使用 .build 来表示复数/多个关联,而 build_ 来表示单数

关于ruby-on-rails - Ruby on Rails : Polymorphic Association with Nested Attributes, 字段未显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22122823/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com