Lighthouse has a new layout. Prefer the old one? Return to the old layout, and switch back any time from the link at the top of each page.

This project is archived and is in readonly mode.

Validations on nested attributes fail on nil foreign key on object creation

#4599

Hello,

class Tag
  belongs_to :post
  validates_presence_of :post
end

class Post
  has_many :post_tags
  accepts_nested_attribute_for :post_tags
end

On Post creation save fails because tag's post is not yet set to the new Post id.

In facts, if the validation is removed the save is successful and the post_id is correctly filled in.

Reported by Daniele Orlandi · May 15th, 2010 @ 12:50 AM

State: resolved
Milestone: none
Assigned to: Neeraj Singh Neeraj Singh
Importance: Low

Activity

  1. Santiago Pastorino
  2. Subba
    Subba
    • Importance changed from to Low

    Daniele try this it will fix above problem.

    
    class Tag
      belongs_to :post,:inverse_of => :post_tags
      validates_presence_of :post
    end
    
    class Post
      has_many :post_tags, :inverse_of => :post
      accepts_nested_attribute_for :post_tags
    end
    

    July 16th, 2010 @ 08:17 PM

  3. Subba
    Subba
    • Assigned user set to Neeraj Singh

    July 16th, 2010 @ 08:17 PM

  4. Neeraj Singh
    Neeraj Singh
    • State changed from new to resolved

    Solution proposed by Subba works for me. Marking it as resolved. If it is still an issue then let's discuss.

    July 19th, 2010 @ 01:26 AM