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.

Not saved children does not have parent object in has many association

#5118

We have got 2 objects in has_many relation

class User
 has_many :movies
end
class Movie
 belongs_to :user
end

If you create a parent object and the children then you have not access to parent object from children until you saved it.

user = User.new
movie = Movie.new
user.movies << movie

user.movies
>> [#<Movie id: nil>]
movie.user
>> nil

In my opinion children should always have information about its parent. It can be usefull if you need this information to prepare object before saving(or in validations).

Reported by Staszek · July 15th, 2010 @ 10:58 AM

State: resolved
Milestone: none
Assigned to: nobody
Importance: Low

Activity

  1. Staszek
    Staszek
    • Tag changed from associations, association_collection, belongs_to, hasmany to 2.x, associations, association_collection, belongs_to, hasmany

    July 15th, 2010 @ 10:59 AM

  2. Subba
    Subba

    you should try using inverse_of option as shown below.

    class User
     has_many :movies, :inverse_of => :user
    end
    class Movie
     belongs_to :user, :inverse_of => :movies
    end
    

    July 15th, 2010 @ 12:50 PM

  3. Staszek
    Staszek

    Thank you. It looks like after #3533 Backport :inverse_of from 3.0 to 2.3.x documentation should be updated. Rdocs for 2.3.8 does not have any information about this option

    July 15th, 2010 @ 01:16 PM

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

    July 15th, 2010 @ 01:41 PM