[英]How to apply conditions when accessing records using a has_many through relationship in 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.