在has_many中通过有没有办法直接引用连接表?
您可以在 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以在 Position 类上添加查找器:
这应该允许您执行以下操作:
You could add the finder on the Position class:
This should allow you to do: