rails fields_for未在子模型上设置父ID

时间:2012-09-10 07:24:14

标签: ruby-on-rails callback fields-for

我一直在使用NestedAttributesFormHelper的rails api文档并搜索stackoverflow。

我在new.html.haml视图中有以下代码:

=form_for listing, :html => {:id => :listing_form, :multipart => :true} do |f|
    =f.fields_for :main_picture, (listing.main_picture || listing.build_main_picture) do |fmp|
            =fmp.hidden_field :main, :value => 1
            =fmp.file_field :image, :class => :picture_select

我控制器中的以下代码:

  def create
    @listing = Listing.new(params[:listing])

    @listing.save ? redirect_to(:root) : render('listings/new')
  end

这是我的listing.rb:

class Listing < ActiveRecord::Base
  has_one :main_picture, :class_name => "Picture", :conditions => {:main => true}
  attr_accessible :main_picture_attributes
  accepts_nested_attributes_for :main_picture, :allow_destroy => true
end

我的照片.rb:

class Picture < ActiveRecord::Base
  belongs_to :listing
  validates_presence_of :listing
  attr_accessible :listing, :main
end

当我尝试提交表单时收到以下错误消息:

main_picture.listing: can't be blank

我无法解决为什么框架没有自动将main_picture(对象图片)的listing_id字段设置为父列表对象的id值。

我做错了吗?

1 个答案:

答案 0 :(得分:3)

您需要validates_presence_of :listing吗?我怀疑子记录是在父对象之前创建的,因此它还没有ID。

删除该行并将:dependent => :destroy添加到has_one :main_picture将确保您不会获得孤儿图片记录。

或者,重写您的控制器:

p = params[:listing]
@listing = Listing.new(p)
@picture = Picture.new(p.delete(:main_picture).merge({:listing => @listing})

etc.