首先,我遵循此处针对 Rails 问题找到的做法(好主意!):https://gist.github.com/1014971
但是我收到错误:
undefined method `search' for #<Class:0x5c25ea0>
app/controllers/accessories_controller.rb:6:in `index'
我确实将我的/app/models/concerns/目录加载到/config/application.rb中。所以“关注”模块正在加载。只是想指出这一点。
这是我的代码:
/app/models/concerns/searchable.rb
module Searchable
extend ActiveSupport::Concern
# Add a "search" scope to the models
def self.search (search)
if search
where('name LIKE ?', "%#{search}%")
else
scoped
end
end
end
/app/models/accessory.rb
class Accessory < ActiveRecord::Base
include Searchable
...
end
/app/controllers/accessories_controller.rb
class AccessoriesController < ApplicationController
def index
@accessories = Accessory.search(params[:search])
...
end
end
最佳答案
好吧,经过一番尝试,我发现了问题所在!
当您想要直接从模块(关注点)内修改模型时,您需要将功能包装在 included block 中。
我已将我的关注模块更改为以下内容:
module Searchable
extend ActiveSupport::Concern
included do
# Add a "search" scope to the models
def self.search (search)
if search
where('name LIKE ?', "%#{search}%")
else
scoped
end
end
end
end
就是这样!希望这能帮助其他有同样问题的人!
关于ruby-on-rails - Rails 3 模型关注模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11514744/