user1579627
user1579627

Reputation: 25

How to I make a drop down beside a search box that searches the specific field selected in rails?

Okay so im new to this site but this is what I have:

Report.rb

def self.search(search)  
    if search  
      where('JOBLETTER_CD_NUMBER LIKE ? AND DATE LIKE? AND CUST LIKE ?', "%#{search}%") 
    else  
      scoped  
    end  
  end  
end  

index.html.erb

select_tag "search", options_for_select([ "Job Letter and CD #", "Date", "Cust", "Job", "Date shipped", "Date billed", "Billed by" ], params[:search]) 

form_tag reports_path, :method => 'get' do

text_field_tag :search, params[:search], :class=> "form-search", :align => "right"

<%= submit_tag "Search", :JOBLETTER_CD_NUMBER => nil, :class => "btn btn-success", :align => "right"

reports controller

def index
    @report = Report.paginate(:per_page => 1, :page => params[:page])
    @report = Report.search(params[:search]).paginate(:per_page => 1, :page => params[:page])  
    respond_to do |format|
      format.html # index.html.erb
      format.json { render :json => @views }

    end
  end

The only field it will search is the Job Letter and CD # field I need it to allow me to search whatever is selected in the drop down box. Btw I am using bootstrap fro js and css functions.

Upvotes: 0

Views: 204

Answers (1)

Thilo
Thilo

Reputation: 17735

Your query has 3 placeholders ? but passed only one argument "#{search}" - if you run it like that, what you really should be getting is an exceptions stating

ActiveRecord::PreparedStatementInvalid: wrong number of bind variables (1 for 3) ...

Also, your select_tag is outside the form, so it won't be passed to the controller at all. If you move it into the form, you'd have to rename (e.g. to column) it since the name search is already used by the text field. Then you could pass both the column and the search parameters to your search function to construct the query.

HOWEVER, this is not safe, since nothing prevents a user to pass in any other column by manipulating the post request, and since you can't use placeholders for column names, there's a danger of SQL injection as well.

There are many solutions out there to construct searches, no need to reinvent the wheel. Take a look at the ransack gem. Here's a recent Railscast on how to use it.

Upvotes: 1

Related Questions