0

我想有一种奇怪的联想。可以说我有以下课程:

class Kid < ActiveRecord::Base
    belongs_to :parent
    has_one :friend
end

class Friend < ActiveRecord::Base
    belongs_to :kid
end

class Parent < ActiveRecord::Base
    has_many :kids
    has_one :friend, :through => :kid #This is the "problematic line"
end

我知道最后一个关系(has_one :friend)是不可能的并且没有意义。但是可以说我知道第一个孩子的朋友总是有足够的信息用于我的父母实例,所以我想像'parent.friend'一样得到它而不是parent.kids.first.friend

4

1 回答 1

0

不,这没有任何意义。如果父母有很多孩子,那么他们不能只有一个朋友,他们的朋友会和有孩子一样多。

Parent.friend 没有任何意义 - 哪个孩子的朋友?

如果它总是第一个,请创建一个函数:

def first_friend
  kids.first.friend
end

如果你想要朋友列表...

def friends
  kids.map(&:friend)  # note this queries immediately, it is not a named scope
end

如果您想从另一个方向获取父母的朋友列表,请在 Friend 模型中使用命名范围:

named_scope :for_parent, lambda {|p| joins(:kids).where('kids.parent_id = ?', p)}
于 2013-04-14T12:43:09.250 回答