Ruby on rails 建立关系后,外键仍然为零
创建地址为的新用户时出现问题。我在Users和Addresses表中创建了记录,但user中address的外键仍然是nilRuby on rails 建立关系后,外键仍然为零,ruby-on-rails,ruby-on-rails-4,Ruby On Rails,Ruby On Rails 4,创建地址为的新用户时出现问题。我在Users和Addresses表中创建了记录,但user中address的外键仍然是nil 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.
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
class用户:新建
结束
结束
私有的
def用户参数
参数require(:user).permit(
:名字,
:姓,
:电邮,
:密码,
:密码\u确认,
地址属性:[:id,:city]
)
结束
结束
谢谢。您混淆了关系类型。 试试这个:
class User < ActiveRecord::Base
has_one :address
end
class Address < ActiveRecord::Base
belongs_to :user
end
class用户
此外,您的代码的结构也很有趣,有两个模型,然后是一些脱离上下文的方法。我希望这只是印刷错误。如果没有,则将除地址
模型之外的所有内容放入用户
模型。我认为#新建#创建和#用户#参数是UsersController的操作