0

I'm having problems when I'm trying to put a condition in params in my controller. This code is inside my controller:

if params[:example] == 1
   @table = Model.find(:all,:conditions=>['column_table= ?',params[:example]  ]  )
else
   @table = Model.find(:all,:conditions=>['column_table2= ?',params[:example]  ]  )
end

Is this code correct? How can I put a conditional in params controller?

sawa
  • 165,429
  • 45
  • 277
  • 381
Charlie Brown
  • 219
  • 3
  • 10

4 Answers4

2

You code looks okay. Unfortunately you do not say what problem you have. The only thing I see that may fail is the condition. If you pass some value into your params they are not typecasted. Therefore I guess you should use to_i in your condition:

if params[:example].to_i == 1
  ...
spickermann
  • 100,941
  • 9
  • 101
  • 131
1

Try with

@table = Model.where((params[:example] == 1 ? 'column_table= ?' : 'column_table2 = ?'), params[:example]) unless params[:example].blank?
Bachan Smruty
  • 5,686
  • 1
  • 18
  • 23
1

Here is code. You have save params[:example] in one variable.and use your coditions.

if params[:example].present?
    @example = params[:example]
   if @example == 1
    @table = Model.find(:all,:conditions=>['column_table= ?',params[:example]  ]  )
    else
   @table = Model.find(:all,:conditions=>['column_table2= ?',params[:example]  ]  )
end
user2310209
  • 992
  • 1
  • 12
  • 27
1

You can also send the column name along with its value and avoid ifs

@table = Model.find(:all,:conditions=>["#{params[:col]} = ?", params[:example]  ]  ) 
techvineet
  • 5,041
  • 2
  • 30
  • 28