简体   繁体   中英

search database in ror

i am new in RoR. According to the book (ruby on rails 4th edition) i have finish it. but i am trying to make a search option for the customers to find the product more easer. I am trying with this example http://railscasts.com/episodes/37-simple-search-form

i have put in views>store>index this:

<%= form_tag products_path, :method => 'get' do %> 
  <p>
    <%= text_field_tag :search, params[:search] %>
    <%= submit_tag "Search", :name => nil %>
  </p>
<% end %>

in the models>products i have put this:

def self.search(search)
  if search
    find(:all, :conditions => ['title LIKE ?', "%#{search}%"])
  else
    find(:all)
  end
end

and in controllers>store_controller this:

 @products = Product.search(params[:search])

the problem is when i am searching is shows me all the products i have and not only what i search and the url is changing to ...../?utf8=%E2%9C%93&search=iphone+4

any ideas plz?

<% form_tag ...

has to be:

<%= form_tag ...
  ^

ok i found it!!! FINALLY...

in the store_controller i was having in the def index this line : @products = Product.all and cause the problem. no the store_controller is:

class StoreController < ApplicationController
    skip_before_filter :authorize
        @products = Product.all
  def index
    @products = Product.search(params[:search])

    @cart = current_cart
  end
end

AND WORKS LIKE CRAZY!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM