2017-08-18 60 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])