繁体   English   中英

存在has_many关系时如何在Rails中返回不同的记录?

[英]How to return distinct records in Rails when there is a has_many relationship?

在Rails 5应用程序中,我有一个表,该表是链接具有很多关系的2个其他表的表。 另外两个表是“组”和“反射”。

我正在尝试编写一个查询,该查询返回用户所在的所有记录。

@reflections = Groupreflectionlookup.where(group_id: @groups_user_is_in).reverse

但是,当我这样做时,由于相同的反射可以存在于多个组中,因此有时同一记录会重复两次。 见下图:

我该如何编写查询,使得虽然最初只返回两条记录,但随后仅返回不同的“ reflection_ids”?

组:

class Group < ApplicationRecord
    belongs_to :user

  extend FriendlyId
  friendly_id :name, use: :slugged

  has_many :groupreflectionlookups
  has_many :reflections, :through => :groupreflectionlookups
end

反射

class Reflection < ApplicationRecord
    belongs_to :user

    has_many :comments

    has_many :userreflectionlookups
    has_many :users, :through => :userreflectionlookups

    has_many :groupreflectionlookups
    has_many :groups, :through => :groupreflectionlookups


end

模式的一部分

  create_table "groups", force: :cascade do |t|
    t.string "name"
    t.integer "user_admin_id"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.string "slug"
    t.integer "user_id"
    t.index ["slug"], name: "index_groups_on_slug", unique: true
  end

  create_table "reflections", force: :cascade do |t|
    t.text "reflection"
    t.integer "user_id"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.text "thorns"
  end

在此处输入图片说明

@reflections = Groupreflectionlookup.select(:reflection_id).distinct.where(group_id:@groups_user_is_in).reverse

这可能是更有意义的定义distinct的条款has_many关系本身,例如。

has_many :groups, -> { distinct }, through: :groupreflectionlookups

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM