所以...我一直在为rails应用程序创建搜索表单。我已经通过了第37,111和112集的导览。Rails根据多个参数使用表格搜索模型
尽管使用文本输入字段的简单文本搜索有效。我需要能够定义更多参数来优化搜索。
我发现其他一些方法,一些使用范围......我一直运行到获得任何这些在我的应用程序工作问题....
我现在所拥有的是定义一个简单的表格在我家的索引指向我的资产指数:
<% form_tag assets_path, :method => 'get' do %>
<%= text_field_tag :search, params[:search] %>
<%= collection_select(:type_id, :type_id, Type.where("type_for = 'asset'"), :id, :name) %>
<%= submit_tag "Search", :search => nil %>
<% end %>
我asset.rb型号:
class Asset < ActiveRecord::Base
has_many :children_assets, :class_name => "Asset"
has_and_belongs_to_many :groups, :join_table => "assets_groups"
belongs_to :parent_asset,
:class_name => "Asset",
:foreign_key => "parent_asset_id"
belongs_to :asset_type,
:class_name => "Type",
:conditions => "type_for = 'asset'"
belongs_to :asset_status,
:class_name => "Status",
:conditions => "status_for = 'asset'"
belongs_to :location
belongs_to :funding_source
has_many :transactions
def self.search(search)
if search
find(:all, :conditions => ['nmc_name LIKE ? AND type_id = ?', "%#{search}%", "%#{search}"])
else
find(:all)
end
end
end
在asset_controller.rb
def index
unless params[:search].nil?
@title = "Assets"
@search = params[:search]
@assets = Asset.search(params[:search]).paginate(page: params[:page], per_page: 25)
else
@title = "Assets"
@assets = Asset.where('').paginate(page: params[:page], per_page: 25)
end
end
我只是不明白这是什么,我没有看到这里。我可以运行一个类似的mysql查询并获得我想要的结果。我只是不知道如何格式化在轨道上...
任何关于此的指导将是惊人的。谢谢!
看起来不错,我 - 是什么你收到的问题?你看到任何错误? –
咋一看,'self.search'方法不应该在SQL中使用'OR'子句而不是'AND'?我假设用户将搜索文本,并且'type_id'字段将是一个简单的整数?如果是这样,那么这将永远不会返回结果。 – PaReeOhNos