Ruby on Rails的多态协会嵌套属性,字段没有显示
问题描述:
我有一个多态关联形式,我想建立一个嵌套形式,但字段没有显示出来:Ruby on Rails的多态协会嵌套属性,字段没有显示
的意见/评论/ _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_
奇异
+0
dang,我认为会是这样的......但它仍然没有出现在我看来 – hellomello
呢''是有问题的错字,或者是它的'answer'。 –
@ParitoshPiplewar它的一个错字,谢谢 – hellomello