繁体   English   中英

查询has_and_belongs_to_many的Rails

[英]Rails where query for has_and_belongs_to_many

我有工作坊表和类别表。

车间型号:

  has_many :workshop_categories, dependent: :destroy
  has_many :categories, through: :workshop_categories

类别模型:

  has_many :workshop_categories, dependent: :destroy
  has_many :workshops, through: :workshop_categories

我有一个WorkshopCategory模型:

class WorkshopCategory < ActiveRecord::Base
 belongs_to :workshop
 belongs_to :category
end

我想根据类别查询活动(活动是一个范围)研讨会。 在车间模型中对此进行了尝试:

  def self.browse(params)  
   workshops = Workshop.active.order( "created_at DESC" )
   workshops = workshops.joins(:categories).where(:categories => { :id => params[:category]}) if params[:category].present?
   workshops
  end

但是我得到这个错误:

ActiveRecord::StatementInvalid (PG::AmbiguousColumn: ERROR:  column reference "id" is ambiguous

此查询的正确方法是什么? 我在互联网上可以找到的所有内容都已过时。

此问题是因为类别和研讨会都有列id

您需要执行以下操作:

workshops.joins(:categories).where('category.id = ?', ...)

请注意,它现在如何指定您要引用的id

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM