【问题标题】:Rails association using OR使用 OR 的 Rails 关联
【发布时间】:2017-04-10 16:13:54
【问题描述】:

给定一个具有以下关联的List 模型:

has_many :list_group_memberships, dependent: :destroy
has_many :groups, through: :list_group_memberships
has_many :users, -> { unscope(:order).uniq }, through: :groups, source: :users

基本上我需要返回以下内容,但作为 ActiveRecord::Relation,而不是数组:

def users
  super + [user]
end

理想情况下,users 关系将使用 or 范围,但我无法解决。

【问题讨论】:

    标签: ruby-on-rails postgresql ruby-on-rails-4 activerecord associations


    【解决方案1】:

    你可以在没有 union gem 的情况下做到这一点:

    # app/models/list.rb
    def users_with_current_user
      # Assuming `users` is the has_many :users relation on the list
      # and `user` is a belongs_to relation on this list...
      User.where(id: users).or(User.where(id: user))
    end
    

    这将自动在 list_group_memberships 表上创建一个 INNER JOIN。

    【讨论】:

    • 非常感谢!我去了User.where(id: super).or(User.where(id: user)).uniq
    【解决方案2】:

    我设法使用active_record_union gem 和以下方法解决了这个问题:

    def users
      super.union(User.where(id: user_id))
    end
    

    编辑:我更改了我的实现以使用@mysmallidea 发布的解决方案

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多