开发者

In has_many through is there a way to reference the join table directly?

Can you reference the properties of a join table in a has_many :through relationship?

Classic join relationship:

class Committee
  has_many :positions
  has_many :members, through: :positions
end

class Member
  has_many :positions
end

class Positions
  belongs_to :committee
  belongs_to :member

  attr_accessible :description
end

This gives us a nice way to access members directly from the Committee:

c = Factory :committee
first_member = members.first

Accessing information on the join table via the association

Is there some way to reference the description of the position (which exists on the join table) from this relationship?

e.g.

first_member_description = membe开发者_运维技巧rs.first.proxy.description

If not then what's the cleanest way to access the description of a particular committee member?

Why would I want to do this?

I want to do this because I want to find a committee member by name and then find their description:

i.e.

peters_description = committee.members.find_by_first_name('Peter').proxy.description


You could add the finder on the Position class:

class Position < ActiveRecord::Base
  belongs_to :committee
  belongs_to :member

  attr_accessible :description

  scope :find_all_by_first_name, lambda do |name|
    joins(:member).where("members.first_name = ?", name)
  end
end

This should allow you to do:

peters_description = committee.positions.find_all_by_first_name('Peter').first.description
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜