Rails,与一个模型的 has_many 多态关联
我想要一个模型(事件)与同一用户模型具有多个多态 HABTM 关联。
它应该像这样工作:
事件< ActiveRecord::Base
has_many :admin_users, :through =>; :事件用户,:源=> :userable, :source_type => “用户”
has_many :participating_users, :through =>; :事件用户,:源=> :userable, :source_type => “用户”
has_many :paid_users, :through =>; :事件用户,:源=> :userable, :source_type => “用户”
has_many :done_users, :through => :事件用户,:源=> :userable, :source_type => “用户”
结束
类EventUser < ActiveRecord::Base
belongs_to :userable, :polymorphic =>真实
属于:事件
结束
用户< ActiveRecord::Bas
has_many :event_users, :as => :可用
has_many :事件, :through => :event_users
结束
这几乎可以工作了!问题是 userable_type 为所有不同的关联获取类型“User”。有可能解决这个问题吗?
I would like to have one model (event) that has multiple polymorphic HABTM associations to the same user model.
It should work something like this:
Event < ActiveRecord::Base
has_many :admin_users, :through => :event_users, :source => :userable, :source_type => 'User'
has_many :participating_users, :through => :event_users, :source => :userable, :source_type => 'User'
has_many :paid_users, :through => :event_users, :source => :userable, :source_type => 'User'
has_many :done_users, :through => :event_users, :source => :userable, :source_type => 'User'
endclass EventUser < ActiveRecord::Base
belongs_to :userable, :polymorphic => true
belongs_to :event
endUser < ActiveRecord::Bas
has_many :event_users, :as => :userable
has_many :events, :through => :event_users
end
This almost works!! The problem is though that userable_type gets the type "User" for all diffrent associations. Is it possible to solve this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
恐怕你的联想看起来完全错误。首先,如果关联的一侧有“has_many”,则在另一侧您必须有“belongs_to”。其次,我猜测done_user、admin_user等继承自User。我说得对吗?
Participation_user、admin_user 等彼此有何不同?您真的需要为每个类提供类吗?您可以使用命名范围吗?
我建议你简化你的数据模型。
现在你的模型看起来很模糊。请详细说明一下。
编辑
老实说,我认为你的建模过于复杂。如果我是您,根据您对 *_users 的描述,我只会使用命名范围来检索该类型的用户。所以实际上
现在,在您的 User 模型中编写命名范围来检索 *_user。
这是 named_scopes 上的精彩截屏视频。
I'm afraid your associations look totally wrong. First of all, if you have a 'has_many' on one side of a association, you have to have a 'belongs_to' on the other side. Secondly, I'm guessing done_user, admin_user etc inherit from User. Am i correct ?
And how different are participating_user, admin_user etc different from each other? Do you really need classes for each of these, can you make do with named scopes?
I would suggest you simplify your data model.
Right now your modeling looks fuzzy. Please do elaborate.
EDIT
Honestly, I think your modeling is over complicated. If I were you, given your descriptions of *_users, I would just have named scopes to retrieve that type of an user. So in effect
So now, write named scopes in your User model to retrieve *_user.
Here's an excellent screencast on named_scopes.