2015-10-05 37 views
0

我試圖傳遞一些不屬於模型屬性一部分的額外屬性。將不在模型屬性中的參數列入白名單

def fulfillment_params 
    params.require(:fulfillment).permit(
     :id, :ids, :batch_edit_fulfillment_ids, 
     :remarks, 
    ) 
    end 

我該如何正確地做到這一點? batch_edit_fulfillment_ids是我在其中一種形式中使用的字段,但是當我嘗試執行update(fulfillment_params)操作時,rails會假定這是我的模型中的字段之一,並且引發錯誤,表明模型中沒有此類字段

回答

0

儘量不要將它傳遞給fulfillment_params。使用params[:fulfillment][:batch_edit_fulfillment_ids]

+0

所以你的意思是我不需要在白名單中包含這些參數? – gazubi

+0

是的,你可以,如果它的值是一個字符串或數組。只有當值是散列值時纔是危險的。 你能說出你用這個值做什麼嗎? –

1

如果batch_edit_fulfillment_ids不是表中的字段,那麼您絕對不會更新它。它沒有任何意義。因此,您不需要將其添加到whitelist中,因爲您只將那些可供用戶更新的attributes列入白名單。

欲瞭解更多信息請參閱本:https://cbabhusal.wordpress.com/2015/10/02/rails-strong-params-whilisting-params-implementation-details/

在你的情況下,你可以參考Alex的答案,或者如果你想在模型中訪問該值,則可以將其設置

class Fulfillment < ActiveRecord::Base 
attr_accessor :batch_edit_fulfillment_ids 
end 
# in controller you can set 
@fulfillment.batch_edit_fulfillment_ids = params[:fulfillment][:batch_edit_fulfillment_ids] 
1

試試這個方法:

def fulfillment_params 
    hash = {} 
    hash.merge! params.require(:fulfillment).slice(:id, :ids, :remarks) # model attributes 
    hash.merge! params.slice(:batch_edit_fulfillment_ids) # non-model attributes 
    hash 
end 
相關問題