Rails - 为过滤器创建HBTM范围

时间:2017-08-18 05:50:48

标签: ruby-on-rails postgresql activerecord

我尝试创建一个包含2个参数的过滤器 - 一个用无线电输入编辑,另一个用一组复选框编辑。我有2个模型由has_and_belongs_to_many关联连接。我需要创建一个带有嵌套模型ID的scope。例如,我有网址:

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

范围必须返回带有id s 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

1 个答案:

答案 0 :(得分:0)

请尝试此操作并确保您的中间表名称正确无误(:features_lamps或lamps_features)

$config['resourceTypes'][] = array(
  'name'              => 'Images',
  'directory'         => 'images',
  'maxSize'           => 2000,
  'allowedExtensions' => 'bmp,gif,jpeg,jpg,png',
  'deniedExtensions'  => '',
  'backend'           => 'default'
);