我有一个多态关联表单,我想构建一个嵌套表单,但字段没有出现:
视图/评论/ _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
答案 0 :(得分:0)
我认为你的问题在这里:
<%= 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_
表示单数