2013-09-27 46 views
0

我在嘗試在控制器中將params條件放入時遇到了問題。此代碼位於我的控制器內部:如何在條件控制器中添加條件?

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

此代碼是否正確?我怎樣才能在params控制器中添加一個條件?

+0

所有檢查的首募PARAMS [:示例] .inspect – user2310209

+0

您遇到什麼問題,顯示錯誤.. – tihom

回答

2

你的代碼看起來還好。不幸的是,你不會說你有什麼問題。我看到的唯一可能失敗的就是條件。如果你將一些價值傳遞給你的參數,他們不會被模擬。因此,我想你應該在你的條件下使用to_i

if params[:example].to_i == 1 
    ... 
+0

THanks spickermann它爲我工作 –

1

嘗試用

@table = Model.where((params[:example] == 1 ? 'column_table= ?' : 'column_table2 = ?'), params[:example]) unless params[:example].blank? 
1

這裏是代碼。你可以在一個變量中保存params [:example]並使用你的編碼。

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 
+0

感謝您的幫助! :) –

1

您還可以使用它的值一起發送列名,避免IFS

@table = Model.find(:all,:conditions=>["#{params[:col]} = ?", params[:example] ] ) 
+0

感謝是另一種幫助:) –