Rails 4 nested_attributes with has_one association rollback

时间:2015-01-07 22:39:25

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

我在Rails 4 app中有两个模型,带有has_one关联。

class User < ActiveRecord::Base
  has_one :member
  accepts_nested_attributes_for :member
end

class Member < ActiveRecord::Base
  belongs_to :user
end

我尝试使用会员创建用户。 这是我的控制者。

class UsersController < ApplicationController
  def new
    @user = User.new
    @user.build_member
  end

  def create
    @user = User.new member_params
    if @user.save
      redirect_to users_path
    else
      render action: :new
    end
  end

  private

  def member_params
    params[:user].permit(:id, :name, :email, :password, :city, member_attributes: [ :position, :avatar, :avatar_cache, :user_id ])
  end
end

这是表格。我使用的是SimpleForm。

= simple_form_for @user do |f|
  = f.input :name
  = f.input :email
  = f.input :city
  = f.input :password
  = f.simple_fields_for :member, @user.member do |us|
    = us.input :position
    = us.input :avatar
  = f.button :submit

我的代码中有哪些部分是错误的?

Parameters: {"utf8"=>"✓", "authenticity_token"=>"eqxcHlLrnKB9atm3YGG6WyMT429qqRr5zpB/LM4IMAI=", "user"=>{"name"=>"Павел", "email"=>"kalashnikov@ulmic.ru", "city"=>"Ульяновск", "password"=>"[FILTERED]", "member_attributes"=>{"position"=>"123", "avatar_cache"=>""}}, "commit"=>"Создать User"}
User Load (0.4ms)  SELECT  "users".* FROM "users"  WHERE "users"."id" = 1 LIMIT 1 (0.3ms)  
BEGIN
User Exists (0.5ms)  SELECT  1 AS one FROM "users"  WHERE "users"."email" = 'kalashnikov@ulmic.ru' LIMIT 1 (0.3ms)  
ROLLBACK

此代码在我的Rails 3项目中工作,但Rails 3中没有strong_parameters。

1 个答案:

答案 0 :(得分:1)

验证问题比使用强参数更有可能。在您的情况下,user.email似乎被限制为唯一,但它可以是usermember模型上的任何内容。当然,即使提交了正确的数据,禁用参数也可能是验证失败的原因,但在这种情况下,您将在服务器日志中看到一条消息(但不会抛出任何异常)。