gpt4 book ai didi

ruby-on-rails - RoR - 所有模型的全局方法

转载 作者:行者123 更新时间:2023-12-04 05:43:41 25 4
gpt4 key购买 nike

我遇到了一个小问题,不知道我应该在哪里添加一个所有模型都可以访问它的方法。我阅读了其他类似的帖子,但不太清楚在哪里添加它。他们中的一些人说要把它作为一个模块添加到“/lib”,然后将它包含在模型类中(已经尝试过但没有运气)。那么添加这个的最佳做法是什么?

我正在尝试以下操作:

我的模块在:/lib/search.rb

module Search     
def self.search(params,columns_search)
srch = params[:search]

if srch.blank?
scoped
else
search= []
#Add conditions for the search
columns_search.map do |column|
search << (sanitize_sql_for_conditions ["LOWER(CAST(#{column} as TEXT)) LIKE ?", "%#{srch.downcase}%"])
end

where("(#{conditions.join(" and ")})")

end
end

在我的模型 cars.rb

class Cars < ActiveRecord::Base
include Search

attr_accessible :name

end

但我在控制台上收到以下错误:

Started GET "/cars" for 127.0.0.1 at 2012-08-01 11:56:54 -0500

ActionController::RoutingError (uninitialized constant Car::Search): app/models/car.rb:2:in `'

任何帮助将不胜感激! :)

最佳答案

您提到的技术似乎是一种合理的方法 - 创建一个模块(可能位于 /lib 中)定义您希望模型具有的方法,然后将其包含在每个模型中需要它。

例如,我当前的项目有图像、视频和音频,所有这些都有特定的方法应该可供使用,因为它们都是媒体类型。我在 lib/media.rb 中定义了一个模块:

module Media
def self.included(base)
# Associations etc. go here
base.has_many :things
base.mount_uploader :image, ImageUploader
base.attr_accessible :image
base.before_save :do_something
end

def do_something(argument=nil)
#stuff
end

end

然后在每个媒体模型中,我都包含它:

class Video < ActiveRecord::Base
include Media

end

然后我可以调用 Video.first.do_something,就好像该方法是在模型中定义的一样。

关于ruby-on-rails - RoR - 所有模型的全局方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11763679/

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