未定义的方法`to_key&#39;对于#<user :: activerecord_relation:0x007f1bf8c2fd60>

时间:2016-09-14 09:55:53

标签: ruby-on-rails ruby activerecord

我是铁杆的新人,所以请原谅我,如果我看不到它。

我正在尝试编辑每个用户的权限,我在form_for中收到此错误:

undefined method `to_key' for #<User::ActiveRecord_Relation:0x007f1bf8c2fd60>

从我在stackoverflow上的其他问题上看到的情况,当你尝试在表单中调用集合时通常会发生这种情况但事实并非如此?

视图:

<div class="n-container">
<tr-form data-riot riot-tag="tr-form">
<%= form_for(@user) do |f| %>

    <section>
        <div class="w-container">
            <h1>User permissions</h1>
            <% @permissions.each do |permission| %>
                <%= check_box_tag 'permission_ids[]', permission.id %>
                <div>
                    <%= permission.description %>
                </div>
            <% end %>
        </div>
    </section>

    <section>

      <div class="f-controls align-right">
        <%= f.submit class: "btn fill blue", value: "Submit" %>
      </div>

    </section>
<% end %>
</tr-form>
</div>

users_controller:

class UsersController < ApplicationController
    def user_params
        params.require('user').permit(
            permissions: []
        )
    end

    def permissions
        @user = User.where(id: params[:user_id])
        @permissions = Permission.all
    end
end

路线:

resources :users do
  get 'permissions'
  post 'permissions'
end

提前谢谢!

1 个答案:

答案 0 :(得分:2)

应该使用ActiveRecord::FinderMethods#find而不是where来接收单个实例:

def permissions
    # WRONG: where returns a relation
    # @user = User.where(id: params[:user_id])
    @user = User.find(params[:user_id])
    @permissions = Permission.all
end

值得一提的是,find在失败时引发RecordNotFound例外,因此您可能希望从中解救:

def permissions
    @user = User.find(params[:user_id])
    @permissions = Permission.all
rescue RecordNotFound => rnf
    # Log or just skip
end

where也可能在这里[ab]使用,但在这种情况下,您需要明确说明您需要唯一的用户:

@user = User.where(id: params[:user_id]).first