簡體   English   中英

Rails ::參數缺失或值為空

[英]Rails:: param is missing or the value is empty

我正在嘗試為商品添加一個收藏夾選項。 允許用戶將特定項目添加到收藏夾列表中。 但是我得到這個錯誤:

param is missing or the value is empty: favorite

收藏夾控制器中的create方法:

def create
@favorite = Favorite.new(params.require(:favorite).permit(:item_id, :user_id ))
if @favorite.save
  redirect_to @favorite
   flash[:notice] = 'Favorite was successfully created.' 
else
  render 'new'
end
end

該項目的視圖顯示:

<%= link_to 'Add to favorites', {:controller => "favorites", 
                   :action => "create", 
                   :item_id => @item.id, 
                   :user_id => current_user.id},
                   :method => "post" %>

請求(參數):

{ "_method"=>"post", "authenticity_token"=>"Wz1eGNw/3GH9t+aOquT/hu1F27zBSqAx6K6igxoc2VI=", "item_id"=>"27",  "user_id"=>"10"}

網址:

/favorites?item_id=27&user_id=10

如果您查看ActionController#permit的文檔,則似乎需要將參數嵌套在“收藏夾”下:

(favorite: { item_id: 1, user_id: 1 })

當使用諸如form_for的rails表單助手時,該嵌套會自動完成,但是因為您是通過link_to item_id手動傳遞參數,而user_id將直接嵌套在params下。

這樣的答案說明了如何將link_to參數合並到params哈希中。 或者,您可以在調用params.require之前將它們合並到控制器中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM