You don't have these methods:
User.family.new
User.child.new
When you define has_many
association, you just have these methods to create new object associated:
collection.build(attributes = {}, …)
collection.create(attributes = {})
Follow Rails guide:
collection is replaced with the symbol passed as the first argument to has_many
You can look at this has_many association reference for more info.
So, If User
want create new family or child, you need to use these methods:
user = User.create(name: "ABC") # create new user and save to database.
user.families.build # create new family belongs to user
user.children.build # create new children belongs to user
user.families.create # create new family belongs to user and save it to database.
user.children.create # create new child belongs to user and save it to database.
If you want to get children belongs to parent which belongs to family, you can modify your association:
Class Family < ActiveRecord::Base
belongs_to :user
has_many :parents
has_many :children, through: :parents # Get children through parents
end
Class Parent < ActiveRecord::Base
belongs_to: :user
belongs_to: :family
has_many: :children
end
Class Child < ActiveRecord::Base
belongs_to :user
belongs_to :parent
end
Now, you can get all children belongs to parents which belongs to a family ( I suppost family have id = 1) with:
f = Family.find(1) # Find a family with id = 1
f.children # Get all children in family.