Ruby协会:有一个到多个 - 有可能吗?

时间:2013-04-14 12:09:07

标签: ruby-on-rails ruby activerecord associations

我想要一种奇怪的联想。假设我有以下课程:

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

1 个答案:

答案 0 :(得分: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

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

named_scope :for_parent, lambda {|p| joins(:kids).where('kids.parent_id = ?', p)}
相关问题