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

后端 未结 1 856
忘了有多久
忘了有多久 2021-01-25 18:08

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

1条回答
  •  有刺的猬
    2021-01-25 18:40

    the simple way to do it is

    Model.find(:all, :conditions => ['name LIKE ?', "%#{search}%"])

    in View

    <% form_tag projects_path, :method => 'get' do %>
      

    <%= text_field_tag :search, params[:search] %> <%= submit_tag "Search", :name => nil %>

    <% 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
    

    0 讨论(0)
提交回复
热议问题