Ruby on Rails:与嵌套属性的多态关联,字段未显示

时间:2014-03-02 01:42:27

标签: ruby-on-rails ruby ruby-on-rails-3 nested-attributes polymorphic-associations

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

视图/评论/ _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

1 个答案:

答案 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_表示单数