簡體   English   中英

Rails錯誤的參數數量(給定0,應為1)

[英]Rails wrong number of arguments (given 0, expected 1)

我在我的這個方法groups控制器。

def remove
  @usergroup = Usergroup.where(group_id: params[:group_id]).destroy
  redirect_to groups_path
end

<%= link_to 'Remove', { controller: "groups", action: "remove" },
    group_id: @group.id, data: { confirm: 'Are you sure?' } %>

當我單擊刪除並確認刪除時,出現此錯誤。

在此處輸入圖片說明

我有點困惑,因為該組的ID是6,應該是。 對於這個群組,我正在嘗試從某人中刪除某人。 為什么會給我一個沒有參數的錯誤呢?

這是我設定的路線。 我相信這是問題所在。 get 'groups/remove/:id', to: 'groups#remove'

不確定這是否是問題,但您將變量設置為已破壞的內容

我想是因為你使用它的where ,你在試圖調用銷毀對象的名單上,因為當你調用ActiveRecord的.where它返回即使只有一個列表。 您應該嘗試這樣做:

@group = Usergroup.find_by(group_id: params[:group_id])
if @group
  @group.destroy
...

並使您的link_to像這樣:

<%= link_to 'Remove', name_of_path_here_path(group_id: @group.id), confirm: 'Are you sure?', method: :delete %>

此外,請記住,您可以使用Rails: routes.rb中常用的Restful路由模式(例如: resources :usergroups )。 您也可以使用as: :name_of_route_here路由別名as: :name_of_route_here 要仔細檢查您的路由,您可以打開終端並運行bundle exec rake routes並且在bundle exec rake routes的左列上是路由助手的名稱。 希望這可以幫助。

在使用where ,它返回Model::ActiveRecord_Relation ,然后您需要“標識”要銷毀的對象,即訪問單個元素,可以通過訪問結果中的特定元素來實現,喜歡:

Usergroup.where('group_id = ?', params[:group_id]).first.destroy

或者使用destroy_all ,它將獲取結果中的所有對象並銷毀所有對象:

Usergroup.where('group_id = ?', params[:group_id]).destroy_all

您的參數是id = 6而不是group_id = 6

暫無
暫無

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

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