如何知道关联对象是仅仅是构建的对象还是Rails中保存的对象?

时间:2017-09-05 21:19:17

标签: ruby-on-rails rails-activerecord

我有以下两种模式:

class User < ApplicationRecord
  has_many :authentications
end

class Authentication < ApplicationRecord
  belongs_to :user
end

假设我们有以下代码:

user1 = User.find(1)
user1.authentications.build(some_authentication_params)

user2 = User.find(2) # This user has already an associated authentication that is saved in the database.

我的问题是:如何区分user1&amp; user2就相关的身份验证而言?{/ p>

到目前为止我做了什么:

def has_active_authentications?
  authentications.all? &:persisted?
end

仅用于构建身份验证:

def has_any_built_authentication?
  authentications.any? &:new_record?
end

有没有更好的方法来完成这项工作?

0 个答案:

没有答案