Rails - 嵌套强参数
Rails - Nested Strong parameters
我正在尝试使用两个模型用户和个人资料创建用户注册,在一个控制器中嵌套强参数。当我发送参数时,我得到了用户的这个错误未知属性 '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
如果是 has_one
,则使用单数 profile_attributes
我正在尝试使用两个模型用户和个人资料创建用户注册,在一个控制器中嵌套强参数。当我发送参数时,我得到了用户的这个错误未知属性 '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
如果是 has_one
profile_attributes