简体   繁体   English

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

[英]rails fields_for parent id not being set on child model

I have been working from the rails api documents for NestedAttributes and FormHelper and searching stackoverflow. 我一直在使用NestedAttributesFormHelper的rails api文档和搜索stackoverflow。

I have the following code in my new.html.haml view: 我在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

And the following code in my controller: 以下代码在我的控制器中:

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

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

Here is my listing.rb: 这是我的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

And my picture.rb: 还有我的照片.rb:

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

And I get the following error message when I try and submit my form: 当我尝试提交表单时收到以下错误消息:

main_picture.listing: can't be blank

I can't work out why the framework is not automatically setting the listing_id field of the main_picture (object Picture) to id value of parent Listing object. 我无法弄清楚为什么框架不会自动将main_picture(对象图片)的listing_id字段设置为父列表对象的id值。

Is there something I am doing wrong? 有什么我做错了吗?

Do you need the validates_presence_of :listing ? 您需要validates_presence_of :listing吗? I suspect that the child record is getting created before the parent object, and so it doesn't have an ID yet. 我怀疑子记录是在父对象之前创建的,因此它还没有ID。

Removing that line and adding :dependent => :destroy to your has_one :main_picture would ensure you don't end up with orphan picture records. 删除该行并将:dependent => :destroyhas_one :main_picture将确保您不会以孤儿图片记录结束。

Alternatively, rewrite your controller: 或者,重写您的控制器:

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

etc.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM