【问题标题】:Rails saving nested ModelsRails 保存嵌套模型
【发布时间】:2016-04-20 17:51:58
【问题描述】:

我有以下型号

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

用户有_许多授权

@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 构建它时它不应该保存

【问题讨论】:

  • 因为@user.idnil,所以没有持久化。
  • @Зелёный 但未保存。当我保存 [at]user 时,它会保存用户,然后它会保存嵌套模型,因此它会自动保存 id 对吗?

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


【解决方案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

【讨论】:

    【解决方案2】:

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

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-02-02
      • 1970-01-01
      • 1970-01-01
      • 2014-04-03
      • 2014-05-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多