在has_many中通过有没有办法直接引用连接表?

发布于 2024-12-03 10:17:46 字数 862 浏览 0 评论 0原文

您可以在 has_many :through 关系中引用联接表的属性吗?

经典连接关系:

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

这为我们提供了一种直接从委员会访问成员的好方法:

c = Factory :committee
first_member = members.first

通过关联访问连接表上的信息

是否有某种方法可以引用以下描述:该关系中的位置(存在于连接表上)?

例如,

first_member_description = members.first.proxy.description

如果不是,那么访问特定委员会成员的描述的最简洁方法是什么?

我为什么要这样做?

我想这样做是因为我想按姓名查找委员会成员,然后找到他们的描述:

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

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 = members.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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

半城柳色半声笛 2024-12-10 10:17:46

您可以在 Position 类上添加查找器:

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

这应该允许您执行以下操作:

peters_description = committee.positions.find_all_by_first_name('Peter').first.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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文