问题
I read through the API for Active Record Querying, but it doesn't seem to include a method for the user to actually input search data. I assume I could somehow link_to a method which contains the query code, but how could I use specific search params? Let's say I only want to search by name for matching instances of one model.
Thanks in advance!
回答1:
the simple way to do it is
Model.find(:all, :conditions => ['name LIKE ?', "%#{search}%"])
in View
<% form_tag projects_path, :method => 'get' do %>
<p>
<%= text_field_tag :search, params[:search] %>
<%= submit_tag "Search", :name => nil %>
</p>
<% end %>
In Controller
def index
@projects = Project.search(params[:search])
end
In Models
def self.search(search)
if search
find(:all, :conditions => ['name LIKE ?', "%#{search}%"])
else
find(:all)
end
end
来源:https://stackoverflow.com/questions/26694416/rails-how-can-a-user-input-data-into-an-active-record-query