ruby-on-rails - rails : How do I define an association extension in a module that gets included in my AR model?

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

我有一个 Blockable包含关联和方法的模块,这些关联和方法将包含在其他一些 ActiveRecord 中类。

相关代码:

module Blockable
  def self.included(base)
    base.has_many :blocks
  end
end

我想添加一个关联扩展。通常的语法(即当我没有在模块中定义关联时)是这样的:
# definition in Model < ActiveRecord::Base
has_many :blocks do
  def method_name
    ... code ...
  end
end

# usage
Model.first.blocks.method_name

在 AR 模型中包含的模块中使用时,此语法不起作用。我得到一个 undefined method 'method_name' for #<ActiveRecord::Relation:0xa16b714> .

知道我应该如何在模块中定义关联扩展以包含在其他 AR 类中吗?

最佳答案

Rails 3 为此提供了一些辅助方法。这个例子来自 The Rails 3 Way, 2nd Edition :

module Commentable
  extend ActiveSupport::Concern
  included do
    has_many :comments, :as => :commentable
  end
end

关于ruby-on-rails - rails : How do I define an association extension in a module that gets included in my AR model?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4892847/

相关文章:

ruby-on-rails - 如何配置 action mailer(我应该注册域)?

javascript - Textmate 中 js.erb 文件更好的语法突出显示

mysql - 您应该在 RoR 中的什么位置存储大量自定义字符串?

sql - Postgres/Rails Active Record——查询四舍五入的浮点值

ruby-on-rails - 将redis部署到heroku无法连接

ruby-on-rails - 我如何运行 rake db :migrate in automated deploy with heroku or heroku-api gem?

ruby-on-rails - 如何在 Rails Controller 中调用 channel 方法?

ruby - 将记录的 created_by 字段检索到 Rails3 中传递的月份和年份?

ruby-on-rails - 事件记录中包含 OR 的 where 子句的正确语法

ruby-on-rails - Rails 将附加参数传递给模型