在Rails 6
, 中Ruby 2.6
,我遇到了一个类似的问题,我有一个User
可以属于许多Organizations
的,但总是有一个是他们被分配到primary_organization
的第一个。Organization
最初我用以下方法设置了这个:
def primary_organization
organizations.first
end
然而,这最终破坏了我的作用域链。上述primary_organization
方法可以重构为可链接的条件,而无需更改user.primary_organization
语法:
用户.rb
# has_many: OrganizationUsers > Organizations
# ==================================================================================
has_many :organization_users,
class_name: 'OrganizationUser',
inverse_of: :user,
dependent: :destroy,
autosave: true,
has_many :organizations,
class_name: 'Organization',
through: :organization_users,
inverse_of: :organization_users,
source: :organization
# *** ADDED IN REFACTOR ***
# has_one: Organization
# shortcut for:
# • `user.organization_users.first.organization`
# • `user.organizations.first`
# ==================================================================================
has_one :primary_organization_user,
-> {
order(
created_at: :desc
).limit(1)
},
class_name: 'OrganizationUser',
inverse_of: :user
has_one :primary_organization,
class_name: 'Organization',
through: :primary_organization_user,
inverse_of: :organization_users,
source: :organization
组织用户.rb
# belongs_to: Organization
# ==================================================================================
belongs_to :organization,
class_name: 'Organization',
inverse_of: :organization_users
# belongs_to: User
# ==================================================================================
belongs_to :user,
class_name: 'User',
inverse_of: :organization_users
组织.rb
# has_many: OrganizationUsers > Users
# ==================================================================================
has_many :organization_users,
class_name: 'OrganizationUser',
inverse_of: :organization,
autosave: true,
dependent: :destroy
has_many :users,
class_name: 'User',
through: :organization_users,
inverse_of: :organization_users,
autosave: true