我发现搜索我特别不希望字符大小写重要的内容的最佳方法是:
@tag = Rails.env.development? ? Category.where("LOWER(name) LIKE ?", "%#{params[:find]}%")[0] : Category.where("LOWER(name) ILIKE ?", "%#{params[:find]}%")[0]
我必须有 .env
查找器,因为我使用 Heroku,而且我不关心在我的开发机器上安装 PostgreSQL。不过,是不是有这样的东西:
@tag = Category.find_by_name(params[:find], case_sensitive: false)
在 Rails 中是否有选项可以传递给 find_by
助手?这将是一个不错的选择。
Are there options that we can pass to the find_by helper in Rails? This would be a nice one...
没有没有。 ( see the API )
是的,那会很不错。
你可能不会接受这个答案,因为你的问题不是真正的问题
这可能就是您被否决的原因。
也许您也可以将 params[:find]
小写(params[:find].downcase
)并注意在您的开发机器上设置 PG。
Category.where("LOWER(name) LIKE ?", "%#{params[:find].downcase}%").first
与此同时,您可以在模型中提取查询:
类别.rb
def self.search_by_name(name)
if Rails.env.development?
where("LOWER(name) LIKE ?", "%#{name.downcase}%").take
else
where("LOWER(name) ILIKE ?", "%#{name}%").take
end
end
控制者
@tag = Category.search_by_name(params[:find])