0

我正在使用 Ruby on Rails v3.2.2。alias_method通过这种方式,我与用于关联的关联具有以下关联has_many :through

class Resource < ActiveRecord::Base
  has_many :article_associations
  alias_method :post_associations, :article_associations

  has_many :users, :through => :post_associations
end

当我执行时,@article.users我收到以下错误:

ActiveRecord::HasManyThroughAssociationNotFoundError
Could not find the association :post_associations in model Article

为什么会发生?有没有办法让它按预期工作?也就是说,如何@article.users通过“aliased”正确返回:post_associations


注意:我想:post_associationshas_many :users, :through => :post_associations语句中“声明”/“使用”,因为我正在尝试“动态构建”(即元编程)has_many :through关联。


Ruby on Rails框架跟踪是:

activerecord (3.2.2) lib/active_record/reflection.rb:501:in `check_validity!'
activerecord (3.2.2) lib/active_record/associations/association.rb:26:in `initialize'
activerecord (3.2.2) lib/active_record/associations/collection_association.rb:24:in `initialize'
activerecord (3.2.2) lib/active_record/associations/has_many_through_association.rb:10:in `initialize'
activerecord (3.2.2) lib/active_record/associations.rb:157:in `new'
activerecord (3.2.2) lib/active_record/associations.rb:157:in `association'
activerecord (3.2.2) lib/active_record/associations/builder/association.rb:44:in `block in define_readers'
...
4

2 回答 2

3

我看不出您需要 alias_method 命名您的关联的原因。

相反,你可以直接做这样的事情,

class Resource < ActiveRecord::Base
  has_many :post_associations, :foreign_key => :resource_id, :class_name => "ArticleAssociation"
  has_many :users, :through => :post_associations
end

另一种解决方案

class Resource < ActiveRecord::Base
  has_many :article_associations
  has_many :users, :through => :article_associations
end

def post_associations
  self.article_associations
end

你需要这样做

resource.post_associations

或者

resource.article_associations
于 2012-10-13T12:18:15.130 回答
0

看起来您正在尝试实现多态关联

于 2012-10-13T12:24:26.830 回答