【问题标题】:Rails wrong number of arguments (given 0, expected 1)Rails 参数数量错误(给定 0,预期 1)
【发布时间】:2017-11-26 22:28:47
【问题描述】:

我的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'

【问题讨论】:

    标签: ruby-on-rails


    【解决方案1】:

    当你使用where,它返回一个Model::ActiveRecord_Relation,那么你需要“识别”你想要销毁的对象,即访问单个元素,你可以通过访问特定元素来做到这一点结果,如:

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

    或者使用destroy_all,它将获取该结果中的所有对象并销毁所有对象:

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

    【讨论】:

    • 在尝试了你的方法后,我似乎得到了这个错误:undefined method destroy' for nil:NilClass`
    • 所以您使用where 的查询结果为空。
    • .where().first => .find_by
    • 请查看更新后的问题。我相信这与路线有关。
    • 您使用的是params[:group_id],但您的路线和参数都显示为id,请尝试在这两种情况下都使用id @TrentonTyler。
    【解决方案2】:

    不确定这是否是问题,但您将变量设置为已销毁的东西

    【讨论】:

      【解决方案3】:

      您的参数是 id =6 而不是 group_id =6

      【讨论】:

      • 这可以作为评论添加 Dave。
      • 是的,很抱歉我的手机掉了。
      【解决方案4】:

      我认为这是因为您使用了where,您试图在对象列表上调用destroy,因为当您调用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 中常用的 Restful 路由模式:routes.rb(例如:resources :usergroups)。您还可以使用 as: :name_of_route_here 为路由命名。要仔细检查您的路线,您可以打开终端并运行bundle exec rake routes,路线的左列是路线助手的名称。希望这可以帮助。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-08-02
        • 1970-01-01
        • 2021-12-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-01-27
        相关资源
        最近更新 更多