我正在使用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
为什么会这样?有没有办法让它按预期工作?也就是说,如何通过&#34;别名&#34;正确地返回@article.users
。 :post_associations
?
注意:我想&#34;陈述&#34; /&#34;使用&#34; :post_associations
语句中的has_many :users, :through => :post_associations
因为我正在尝试动态构建&#34; (即元编程)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'
...
答案 0 :(得分: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
答案 1 :(得分:0)
看起来你正试图实现polymorphic associations。