无法获得嵌套模型以保存在rails 5中

时间:2016-11-16 08:46:59

标签: ruby-on-rails nested-attributes ruby-on-rails-5

我有一个用户,它是帐户的嵌套资源,我正在尝试以1种形式创建帐户和用户。帐户正在正确保存,但没有写入用户记录。

user.rb:

class User < ApplicationRecord
  belongs_to :account
  validates :email, presence: true
end

account.rb:

class Account < ApplicationRecord
  has_many :users, :dependent => :destroy
  accepts_nested_attributes_for :users
end

accounts_controller.rb:

class AccountsController < ApplicationController
  def new
    @account = Account.new
    @user = @account.users.build
  end

  def create
    @account = Account.new(account_params)
    @account.secret = SecureRandom.uuid
    if @account.save
      flash[:success] = "You've successfully created your account, now it's time to create your first team."
      redirect_to dashboard_path
    else
      flash[:danger] = "There was a problem creating your account"
      redirect_to signup_path
    end
  end

  private

    def account_params
      params.require(:account).permit(:name, user_attributes: [:first_name, :last_name, :email, :password, :password_confirmation, :secret])
    end
end

账户/ new.html.erb:

<h1>Signup</h1>
<div class="row">
  <div class="col-md-6 col-md-offset-3">
    <%= form_for(@account) do |form| %>
      <%= form.label "Account name" %>
      <%= form.text_field :name, class: "form-control" %>

      <%= form.fields_for :user do | f| %>
        <%= f.label :first_name %>
        <%= f.text_field :first_name, class: "form-control" %>

        <%= f.label :last_name %>
        <%= f.text_field :last_name, class: "form-control" %>

        <%= f.label :email %>
        <%= f.text_field :email, class: "form-control" %>

        <%= f.label :password %>
        <%= f.password_field :password, class: "form-control" %>

        <%= f.label :password_confirmation, "Confirmation" %>
        <%= f.password_field :password_confirmation, class: "form-control" %>
      <% end %>

      <%= form.submit "Signup", class: "btn btn-primary" %>
    <% end %>
  </div>
</div>

当我提交表格并查看我的日志时,我看到了:

Processing by AccountsController#create as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"p5+CRICRp3ZilIg1NtehEQG7Gh2amnFFUD5NawtqkICJ4uRDvvJxf2WTbd7+rnfG9zdblT1QWgfJ62NNxcc2RA==", "account"=>{"name"=>"Streame", "user"=>{"first_name"=>"Jeremy", "last_name"=>"Kirkham", "email"=>"jeremy@streame.com.au", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]"}}, "commit"=>"Signup"}
Unpermitted parameter: user

1 个答案:

答案 0 :(得分:1)

答案很简单 - 我需要从

更改表单

<%= form.fields_for :user do | f| %>

<%= form.fields_for :users do | f| %>

(注意用户 - &gt;用户)和来自

的控制器

params.require(:account).permit(:name, user_attributes:

params.require(:account).permit(:name, users_attributes:

(再次注意用户 - &gt;用户)。

基本上它归结为多元化!