gpt4 book ai didi

ruby-on-rails - 在 Rails 中干燥我的 has_many

转载 作者:数据小太阳 更新时间:2023-10-29 08:16:10 27 4
gpt4 key购买 nike

我有一个模型类,其中包括:

class Group < ActiveRecord::Base
has_many :subscriptions
has_many :users, :through => :subscriptions

has_many :admins, :through => :subscriptions, :source => :user, :conditions => "subscriptions.role = #{ROLES[:admin]}"
has_many :subscribers, :through => :subscriptions, :source => :user, :conditions => "subscriptions.role >= #{ROLES[:subscriber]}"
has_many :authors, :through => :subscriptions, :source => :user, :conditions => "subscriptions.role >= #{ROLES[:author]}"
has_many :pending_subscribers, :through => :subscriptions, :source => :user, :conditions => "subscriptions.pending = true"
end

:through => :subscriptions, :source => :user 的重复次数让我很困扰。我知道在路由文件中,您可以执行 map.with_options。我的模型协会有类似的东西吗?

最佳答案

with_options 实际上是对 Object 的扩展, 所以你也可以在你的 ActiveRecord::Base 中使用它

with_options :through => :subscriptions, :source => :user do |obj|
obj.has_many :admins, :conditions => "subscriptions.role = #{ROLES[:admin]}"
obj.has_many :subscribers, :conditions => "subscriptions.role >= #{ROLES[:subscriber]}"
obj.has_many :authors, :conditions => "subscriptions.role >= #{ROLES[:author]}"
obj.has_many :pending_subscribers, :conditions => "subscriptions.pending = true"
end

关于ruby-on-rails - 在 Rails 中干燥我的 has_many,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1168699/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com