【问题标题】:How to properly use a has_many :through with an alias_method?如何正确使用 has_many :through 和 alias_method?
【发布时间】:2012-10-13 11:31:36
【问题描述】:

我正在使用 Ruby on Rails v3.2.2。我与用于has_many :through 关联的alias_method 有以下关联,这样:

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

为什么会这样?有没有办法让它按预期工作?即如何通过“别名”:post_associations正确返回@article.users


注意:我想在 has_many :users, :through =&gt; :post_associations 语句中“声明”/“使用”:post_associations,因为我正在尝试“动态构建”(即元编程)@ 987654330@协会。


Ruby on Rails Framework Trace 是:

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'
...

【问题讨论】:

  • 您能否详细说明为什么需要为您的关联设置别名?我认为没有一种方法可以轻松实现关联别名,因此它有助于了解您需要什么来帮助您解决此限制。
  • @Vincent Robert _ 这是因为我试图将文章抽象为 Mixin 模块中的帖子。也就是说,我希望在 Mixin 模块中,这篇文章完全被视为一篇文章。从那以后,我想alias_method :post_associations, :article_associations 即使是为了协会。

标签: ruby-on-rails ruby ruby-on-rails-3 activerecord associations


【解决方案1】:

我看不出您需要为您的关联命名的 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

【讨论】:

  • 我解释了“为什么我需要alias_method 命名我的协会”以回应@Vincent Robert 对该问题的评论。
  • 如果您需要这样做,请尝试添加一个名为 post_associations 的方法并在资源对象上调用此方法,然后定义将只调用 article_associations。
  • 我完全不明白。你能更明确一点(也许有一个例子)?
  • 我添加了一个替代解决方案
  • 我看到了你的回答。谢谢,但我需要在has_many :users, :through =&gt; :post_associations 声明中“声明”/“使用”它(如问题中所述)。这是因为我会“动态构建”(元编程)has_many :through 关联。
【解决方案2】:

看起来您正在尝试实现polymorphic associations

【讨论】:

  • 不,我不想实现多态关联。我真的不需要那个。
猜你喜欢
  • 1970-01-01
  • 2017-12-09
  • 1970-01-01
  • 2012-03-09
  • 1970-01-01
  • 1970-01-01
  • 2019-03-04
  • 2011-06-07
相关资源
最近更新 更多