gpt4 book ai didi

ruby-on-rails - Rails 3 模型关注模块

转载 作者:行者123 更新时间:2023-12-03 00:47:33 25 4
gpt4 key购买 nike

首先,我遵循此处针对 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com