簡體   English   中英

Rails - 在 has_many 上使用 join model 過濾

[英]Rails - filter using join model on has_many through

如何通過關系為鏈接 has_many 的設施在 Place 表上添加過濾器?

這是所有模型的樣子:

class Place < ApplicationRecord
  has_many :facilities, through: :place_facilities
  has_many :place_facilities, dependent: :destroy

class PlaceFacility < ApplicationRecord
  belongs_to :place
  belongs_to :facility
end

class Facility < ApplicationRecord
  has_many :places, through: :place_facilities
  has_many :place_facilities
end

我希望用戶能夠過濾具有特定設施的地方。

使用joinswhere非常容易

my_places = Place.joins(:facility).where(facilities: {name: 'blackboard'})
Place.includes(:facilities).where(facilities: { attribute: "specific" })

有關詳細信息,請參閱https://guides.rubyonrails.org/active_record_querying.html#specifying-conditions-on-eager-loaded-associations

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM