pokrovskyy
pokrovskyy

Reputation: 487

Ruby on Rails - save new record with nested association requiring this record

I have an issue creating a new record with nested associations in a clean way. Here's the controller code:

@listing = current_user.listings.build(params[:listing].permit(ATTRIBUTES_FOR_CREATE))

This builds an entity with several nested associations, like this:

class ListingDataField < ActiveRecord::Base
  belongs_to :listing
  validates_presence_of :listing
end

However, when I do @listing.save in controller, I get validation errors on those nested ListingDataField entities that 'listing can't be blank'. If I understand correctly, AutosaveAssociation first validates and saves nested associations, and eventually saves top-level entity. Thus, it fails validating ListingDataField, because Listing is not yet saved.

But I believe it's right having :listing validation in ListingDataField, so I wouldn't consider removing this. I can see 2 solutions:

  1. in transaction - save Listing record, then build nested associations one by one
  2. @listing.save(:validate => false) but this is too ugly

Both aren't as much elegant as current_user.listings.build(...), so my question is - what is the proper Rails way for this?

P.S. I searched SO for similar question but I couldn't find any, hopefully this is not a duplicate :)

Upvotes: 3

Views: 252

Answers (1)

Rodrigo Martinez
Rodrigo Martinez

Reputation: 711

Have you tried adding:

class ListingDataField < ActiveRecord::Base
  belongs_to :listing, inverse_of: :listing_data_fields
  validates :listing, presence: true
end

and

class Listing < ActiveRecord::Base
  has_many :listing_data_fields, inverse_of: :listing
end

This should make validation of presence work.

Upvotes: 4

Related Questions