Question

I have been working from the rails api documents for NestedAttributes and FormHelper and searching stackoverflow.

I have the following code in my new.html.haml view:

=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:

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:

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.

Is there something I am doing wrong?

Était-ce utile?

La solution

Do you need the 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.

Removing that line and adding :dependent => :destroy to your has_one :main_picture would ensure you don't end up with orphan picture records.

Alternatively, rewrite your controller:

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

etc.
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top