2017-08-18 61 views
0

我正在嘗試創建一個帶有2個參數的過濾器 - 一個是用無線電輸入編輯的,另一個是用一組複選框編輯的。我有2個模型由has_and_belongs_to_many關聯連接。我需要創建一個scope與嵌套模型的ID。例如,我有網址:Rails - 爲過濾器創建HBTM範圍

/catalog?category=1&feature=1,2 

和範圍必須返回id的1和2

如何創建這樣的範圍內嵌套的實例?

我的類別型號:

class Lamp < ActiveRecord::Base 

    belongs_to :category, inverse_of: :lamps 
    has_and_belongs_to_many :features 

    validates :name, :preview, :small_preview, presence: true 

    scope :visibles, -> { where(hided: false) } 
    scope :category_filter, -> (category_id) { where(category_id: category_id) if category_id.present? } 


end 

我的特徵模型:

class Feature < ActiveRecord::Base 

    has_and_belongs_to_many :lamps 

    validates :name, presence: true 
    validates :name, uniqueness: true 

    mount_uploader :ico, FeatureIcoUploader 

    scope :visibles, -> { where(hided: false) } 
    scope :ordered, -> { order(prior: :asc, id: :desc) } 

    def display_name; name end 

end 
+0

你可以請添加這兩種模式? – Sunny

+0

@孫尼,將其添加到我的問題。夠了嗎? – crcerror

回答

0

請試試這個,並確保你的中間表的名稱是正確的(:features_lamps或lamps_features)

Lamp.joins("join features_lamps on lamps.id = features_lamps.page_id").where(["features_lamps.features_id = ?", features_id])