gpt4 book ai didi

ruby-on-rails - 在 Ruby on Rails 中的 MongoDB 中搜索两个条件

转载 作者:可可西里 更新时间:2023-11-01 09:58:15 25 4
gpt4 key购买 nike

我正在使用 rails cast 视频 http://railscasts.com/episodes/240-search-sort-paginate-with-ajax .我必须使用两个条件在我的数据库中进行搜索。

# In my form for search 
<%= form_tag products_path, :method => 'get', :id => "products_search" do %>
<p>
<%= text_field_tag :search, params[:search] %>
<%= submit_tag "Search", :name => nil%>
</p>

对于一种情况,这工作正常:

# In my model product.rb
def self.search(search)
if search
where(name: /#{Regexp.escape(search)}/i)
else
scoped
end
end

# In my controller products_controller.rb
@products = Product.search(params[:search]).page(params[:page]).per(5)

现在我必须使用另一个参数 role 进行搜索。我的产品模型中有角色字段。角色是 1,2,3。如果给定了角色,那么它应该搜索具有给定输入角色的字符串,否则只搜索名称。

def self.search(search,role)
if search
where(name: /#{Regexp.escape(search)}/i)(and role: should be equal to value of role)

此外,我应该对 products_controller.rb 做哪些更改?在我上面的搜索表单中?

最佳答案

不确定 role 是否是您的 Product 模型的一部分,但如果是:

def self.search(paramsname, role = nil) 
if role
@products = Product.where(:name => Regexp.new(name, true), :role => role)
else
@products = Product.where(:name => Regexp.new(name, true))
end
end

关于ruby-on-rails - 在 Ruby on Rails 中的 MongoDB 中搜索两个条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14100575/

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