Rails has_many :through, and Polymorphic Associations 在 Rails3.1.1 里不工作了?

poshboytl · 2011年11月28日 · 最后由 poshboytl 回复于 2012年02月04日 · 4285 次阅读
class User < ActiveRecord::Base
   has_many :memberships
   has_many :accounts, :through => :memberships, :source => 'membershipable', :source_type => 'Account'
   has_many :projects, :through => :memberships, :source => 'membershipable', :source_type => 'Project'
end

class Account < ActiveRecord::Base
  has_many :memberships, :as => :membershipable
  has_many :users, :through => :memberships
end

class Project < ActiveRecord::Base
  has_many :memberships, :as => :membershipable
  has_many :users, :through => :memberships
end

class Membership < ActiveRecord::Base
  belongs_to :user
  belongs_to :membershipable, :polymorphic => true
end

代码很简单,需求就是把 account 和 project 所属的用户都记录在 membership 中。

User.first.projects << Project.first 不工作 NameError: uninitialized constant Membership::Membershipable

不知道大家在 rails 3.1.1 下用 has_many :through 和 Polymorphic Associations 是否出现过这样的问题?

我记得在以前的 rails 版本中是支持的。今天发现 3.1.1 不支持了,feature or bug?

https://github.com/rails/rails/issues/3247

TL;NR: It's a 3.1.1 bug, add :primary_key => :id to belongs_to :membershipable in Membership model as a work around :)

3.1.2/3.1.3貌似已经修复这个bug了。

#1 楼 @jan Perfect answer. And the work around works well.

需要 登录 后方可回复, 如果你还没有账号请 注册新账号