【问题标题】:Rails - Nested Strong parametersRails - 嵌套强参数
【发布时间】:2015-09-20 17:16:59
【问题描述】:

我正在尝试使用两个模型用户和配置文件创建用户注册,在一个控制器中嵌套强参数。当我发送参数时,我为用户收到此错误未知属性“profiles_attributes”。而且我无法创建用户和个人资料:

class User < ActiveRecord::Base
 has_one :profile
 has_many :apartments
 has_many :session

 has_secure_password
 validates :email, presence: true, uniqueness: true
 validates :password, presence: true

 accepts_nested_attributes_for :profile
end


class Profile < ActiveRecord::Base
 belongs_to :user
 belongs_to :city
 has_many :profile_universities
 has_many :universities, through: :profile_universities
 has_many :profile_preferences
 has_many :preferences, through: :profile_preferences
 has_one :photo, :as => :imageable
end


class Api::V1::UserController < ApplicationController
  before_action :user_params 
  def create_without_facebook


    @user= User.new(user_params)
    if @user.save
        @profile = Profile.new(user_params[:profiles_attributes])

        render json:  [@user, @profile]
    else
        render json: @user.errors, status: :unprocessable_entity

    end
  end

  def user_params
    params.require(:user).permit(:email, :password, profiles_attributes: [:first_name, :last_name, :birthday, :gender, :marital_status, :ocupation, :budget, :question, :about, :city])
  end

end

【问题讨论】:

    标签: ruby-on-rails nested-attributes strong-parameters


    【解决方案1】:

    如果是has_one,请使用单数profile_attributes

    【讨论】:

    • 我做了这个更改,创建了用户但没有创建配置文件。这是响应: [{"id":55,"email":"safe77@jdisji.com","password_digest":"$2a$10$OZ1lvo7xXMVILl1uN3ArWePhUDuNOADR8Uve3ao9EY/f1MHu1vBQK","created_at":"2015-07-03T01: 44:04.344Z","updated_at":"2015-07-03T01:44:04.344Z"},{"id":null,"first_name":null,"last_name":null,"birthday":null,"性别":null,"marital_status":null,"职业":null,"预算":null,"问题":null,"about":null,"user_id":null,"city_id":null,"profile_universities_id" :null,"created_at":null,"updated_at":null}]
    • cmets 中的代码格式很糟糕 :( 如果您尝试了某些方法但它不起作用 - 您可以修改问题吗?或者提出一个新问题(如果您愿意,可以从这里指向它) )。
    • 注意:您可能需要更新代码中的多个位置,可能还需要更新表单模板,以使其正常工作 - 如果它们都使用profiles_attributes...
    • @SaulFelipeRamirez Taryn 的回答是正确的。您应该在 user_params 方法中使用 profile_attributes。确保在您的 html 表单中也有此更改。要有效地调试它,请使用 byebug 并在创建操作中检查 user_params 方法的输出。
    猜你喜欢
    • 1970-01-01
    • 2013-08-28
    • 1970-01-01
    • 2014-10-20
    • 2013-10-14
    • 2014-08-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多