Rails: How can a user input data into an Active Record Query?

馋奶兔 提交于 2019-12-20 04:38:36

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!