创建具有地址的新用户时遇到问题。我在用户和地址表中创建记录,但在用户中寻址的外键仍为零。
class User < ActiveRecord::Base
belongs_to :address
accepts_nested_attributes_for :address
end
class Address < ActiveRecord::Base
has_one :user
end
def new
@user = User.new
@user.build_address
end
def create
@user = User.new(user_params)
if @user.save
flash[:notice] = "Your account has been created."
redirect_to signup_url
else
flash[:notice] = "There was a problem creating you."
render :action => :new
end
end
private
def user_params
params.require(:user).permit(
:first_name,
:last_name,
:email,
:password,
:password_confirmation,
address_attributes: [:id, :city]
)
end
end
谢谢。
答案 0 :(得分:1)
你混淆了关系类型。 试试这个:
class User < ActiveRecord::Base
has_one :address
end
class Address < ActiveRecord::Base
belongs_to :user
end
此外,您的代码结构有趣,两个模型,然后是其背景下的一些方法。我希望这只是一个错误的印刷品。如果没有,请将除Address
模型之外的所有内容放入User
模型中。