UsersController中的ActiveRecord :: RecordNotFound #create无法找到没有ID的帐户

时间:2014-07-02 16:06:52

标签: ruby-on-rails activerecord rails-activerecord

我一直收到这个错误,我已经看了很多其他问题试图找到答案,但我还没能。任何人都可以帮助我吗?

ActiveRecord::RecordNotFound in UsersController#create
Couldn't find Account without an ID

我的模特

class User < ActiveRecord::Base
  belongs_to :account
end

class Account < ActiveRecord::Base
  has_many :users
  accepts_nested_attributes_for :users
end

用户控制器

def create
  @account = Account.find(params[:id])
  @user = @account.users.build(user_params)
  authorize @user
if @user.save
  redirect_to users_path, notice: 'Successfully created User'
else
  redirect_to users_path, alert: 'Failed to create User'
end

表格

<%= form_for(@user) do |f| %>
  <%= devise_error_messages! %>
  <p>
    <%= f.label :name %>
    <%= f.text_field :name, :autofocus => true, class: 'form-control' %>
  </p>
  <p>
    <%= f.label :account %>
    <%= collection_select(:user, :account_id, Account.all, :id, :name, {prompt: true, class: 'form-control'}) %>
  </p>
  <p>
    <%= f.label :email %>
    <%= f.email_field :email, class: 'form-control' %>
  </p>
  <p>
    <%= f.label :password %>
    <%= f.password_field :password, class: 'form-control' %>
  </p>
  <p>
    <%= f.label :password_confirmation %>
    <%= f.password_field :password_confirmation, class: 'form-control' %>
  </p>
  <%= f.submit 'Create User', class: 'btn btn-primary' %>
<% end %>

我要做的是在创建新User时在表单中选择一个帐户。

2 个答案:

答案 0 :(得分:1)

根据您设置表单的方式,帐户ID将在

params[:user][:account_id]

所以使用

@account = Account.find(params[:user][:account_id])

答案 1 :(得分:0)

您的代码将以嵌套方式结束参数。所以params [:user]是主哈希,并且需要使用该哈希而不是params来获取其他细节。

params[:user][:account_id]

会正常工作。