2012-11-28 30 views
1

我刚完成Michael Hartl Rails教程。试图做我自己的东西。Rails:belongs_to multiple>方法

我很难获得rails来理解我试图创建的关系。我会尽量简化这一点。一个树枝,树枝和树叶将是适合的,但...

我将使用父子格式为例。所以很自然我有用户,并且让我们说用户创建家庭。

所以:

Class User < ActiveRecord::Base 

has_many :families 
has_many :parents 
has_many :children 

end 

Class Family < ActiveRecord::Base 

belongs_to :user 
has_many :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 

正如你所看到的,我希望有一个孩子属于哪个属于家庭的家长,但孩子本身不属于一个家庭除了通过父。可悲的是,如果这不是一个隐喻,但在这种特殊情况下是正确的。 ;)

我已经在家长尝试:

has_many :children, through: :parent 

has_many :children, through: :family 

但没有奏效。

当我尝试使用:

User.family.new 

User.child.new 

...它说,该方法不存在。我认为这意味着它不了解这些关系。

我在做什么错?

如果是相关的,在家庭中,父母,子女,现在的表的唯一事情是这些列:

t.string :content 
    t.integer :user_id 
+0

你调用'User.family.new', 'User.family'是未定义的。一个AR关系不会创建类方法,只有实例方法,所以如果你有'@ parent',你可以调用'@ parent.children',前提是你在父方法中有'has_many:children'。在这种情况下,只需调用'Child.new'或'@ parent.children.build',你需要一个父母来做到这一点 –

+0

原谅我,只需从我的应用程序下载试用我的手,但在教程中有Microposts和Users,当你设置Micropost belongs_to用户和用户has_many Microposts时,你可以做User.microposts或者User.micropost.new。为什么这是不同的? –

+1

'User'的使用是调用名为'User'的模型。它不是一个真正的用户,它是你打电话的模型。 'User.create'会创建一个instancied对象User。例如:'user_object = User.create':'user_object'是一个User类型的实例化对象。 – MrYoshiji

回答

2

您没有这些方法:

User.family.new 
User.child.new 

当你定义has_many协会,你只是有这些方法来创建新的对象关联:

collection.build(attributes = {}, …) 
collection.create(attributes = {}) 

关注的Rails指南:

收集被替换为第一个参数传递的符号 的has_many

你可以看一下这个has_many association reference获取更多信息。 所以,如果User要创建新的家庭或孩子,你需要使用这些方法:

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. 

如果你想获得孩子属于父母,属于家庭,您可以修改您的关联关系:

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 

现在,你可以得到所有的孩子属于父母,属于一个家庭(我suppost家庭有ID = 1):

f = Family.find(1) # Find a family with id = 1 
f.children # Get all children in family. 
+0

谢谢。是的,我试图按照railstutorial的建议来做。而不是做Micropost.create,他建议创建关系,并改为使用user.micropost.create。这正是我想要实现的。我认为你的帖子可能已经解决了我的问题,还不确定。它绝对比微博和平均留言板更复杂。 –

+0

只要尝试一下,如果它解决了您的问题,请将其标记为接受答案;) – Thanh