2013-05-13 74 views
56

在Rails 3,它可以插入像這樣的屬性到PARAMS:軌道4:插入屬性PARAMS

params[:post][:user_id] = current_user.id 

我試圖做同樣的事情在Rails中4,但有沒有運氣:

post_params[:user_id] = current_user.id 

. . . . 


private 

    def post_params 
    params.require(:post).permit(:user_id) 
    end 

Rails忽略了這種插入。它不會拋出任何錯誤,它只是悄然失敗。

回答

115

找到了答案here。您可以使用合併將其插入到params定義中,而不是從控制器操作中插入該屬性。要在我前面的例子擴大:

private 

    def post_params 
    params.require(:post).permit(:some_attribute).merge(user_id: current_user.id) 
    end 
+3

謝謝,我需要使用deep_merge,因爲我的屬性被嵌套... – stephenmurdoch 2013-09-08 19:42:54

+0

@marflar你在params構造函數中使用了'deep_merge'?或者你的控制器的其他地方 – 2014-06-18 00:01:43

+0

這也是我的做法,但我一直在想,必須有一種方法來幹這一點。我所有的50多名控制者在嚴格的參數區域都有類似的.merge聲明。在我的情況下,我將current_user合併到updated_by中。我只在create方法中將current_user合併到created_by中。 – Dan 2014-07-31 16:17:24

27

除了@ timothycommoner的答案,則可以選擇在每個動作基礎上進行合併:

def create 
    @post = Post.new(post_params.merge(user_id: current_user.id)) 
    # save the object etc 
    end 

private 
    def post_params 
    params.require(:post).permit(:some_attribute) 
    end 
+1

嗨,你會怎麼做一個嵌套資源? – Patient55 2015-11-11 16:57:13

+0

我不知道爲什麼,但@ timothycommoner的答案不適合我。只有這一個......我甚至嘗試過「合併!」,但仍然失敗。哦,這很容易讀取,因爲沒有私人方法挖掘,並且在不同的使用情況下更容易更改 – james 2016-01-26 16:32:41

+0

@ Patient55我想你需要'deep_merge',因爲他們在所選答案的評論中討論過。 – Wit 2017-06-28 05:17:17

0

對於這種情況下的替代方法,可以通過scope需要通屬性:

current_user.posts.create(post_params)