Rails保存嵌套模型

时间:2016-04-20 17:51:58

标签: ruby-on-rails validation ruby-on-rails-4

我有以下型号

users (id, name, ...)
authorizations (id, provider, provider_uid, token, user_id, ...)
  

用户has_many授权

@user = User.new(first_name: facebook_client.first_name,
                                 last_name: facebook_client.last_name,
                                 email: facebook_client.email,
                                 bio: facebook_client.bio,
                                 date_of_birth: facebook_client.birthday,
                                 gender: facebook_client.gender,
                                 location: facebook_client.location)

    @user.authorizations.build(
                    provider: 'facebook',
                    provider_uid: facebook_client.user_id,
                    oauth_token: facebook_user_token,
                    social_account: SocialAccount.friendly.find('facebook'))

我有一个验证

validates :user_id, presence: true

由于上述情况,我无法保存@user.save

当我通过@user.authorizations.build

构建它时,我无法理解为什么它不应该保存

2 个答案:

答案 0 :(得分:1)

来自documentation

  

如果您想确定存在关联,则需要测试关联对象本身是否存在,并且不是使用的外键来映射关联。

这意味着您必须将validates :user_id, presence: true验证替换为以下内容:

class Authorization < ActiveRecord::Base
  belongs_to :user
  validates :user, presence: true
end

class User < ActiveRecord::Base
  has_many :authorizations, inverse_of: :user
end

答案 1 :(得分:1)

如果给定代码完成,这只是因为你没有保存(持久化)@user,所以它没有id。它需要一个id来创建一个关联(通过它的id链接到该记录)。

如果您签入代码,您应该看到:

@user = User.new...
@user.id => nil

没有id的记录不能有任何关联(不属于belongs_to)。

相关问题