与同一模型的 Rails 关联
假设我有 2 个表:
Users
user_id name
Tags
tagger_id tagged_id
这描述了您可以的情况
我试图设置的模型是:
class User < ActiveRecord::Base
has_many :tags, :foreign_key => "tagger_id"
end
class Tag < ActiveRecord::Base
belongs_to :tagger, :class => "User"
belongs_to :tagged, :class => "User"
end
我正在尝试设置它,以便当我这样做时:
user.tags
它会返回一个 User 对象列表。在我当前的设置中,它只返回带有 id 而不是对象的实际标签记录。如何设置它才能返回 User 对象列表?
我尝试使用:
has_many :tags, :foreign_key => "tagger_id", :source => :tagged
但没有成功。
Let's say I have 2 tables:
Users
user_id name
Tags
tagger_id tagged_id
This describes a situation where you can
And the models that I'm trying to set up are:
class User < ActiveRecord::Base
has_many :tags, :foreign_key => "tagger_id"
end
class Tag < ActiveRecord::Base
belongs_to :tagger, :class => "User"
belongs_to :tagged, :class => "User"
end
I'm trying to set it up so that when I do:
user.tags
It comes back with a list of User objects. With my current setup, it comes back with just the actual Tag record with ids instead of objects. How do I set it up so it returns a list of User objects?
I tried using:
has_many :tags, :foreign_key => "tagger_id", :source => :tagged
But it didn't work.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您正在寻找 has_many :through。
然后
user.tagged
应该会为您提供所需的用户列表。You're looking for has_many :through.
Then
user.tagged
should give you the list of users you want.