[英]Rails where query for has_and_belongs_to_many
I have workshops table and categories table. 我有工作坊表和类别表。
Workshop model: 车间型号:
has_many :workshop_categories, dependent: :destroy
has_many :categories, through: :workshop_categories
Category model: 类别模型:
has_many :workshop_categories, dependent: :destroy
has_many :workshops, through: :workshop_categories
And I have a WorkshopCategory model: 我有一个WorkshopCategory模型:
class WorkshopCategory < ActiveRecord::Base
belongs_to :workshop
belongs_to :category
end
I want to query active (active is a scope) workshops depending on categories. 我想根据类别查询活动(活动是一个范围)研讨会。 Tried this in workshop model:
在车间模型中对此进行了尝试:
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
But I get this error: 但是我得到这个错误:
ActiveRecord::StatementInvalid (PG::AmbiguousColumn: ERROR: column reference "id" is ambiguous
What is the proper way of this query? 此查询的正确方法是什么? Everything that I can find on the internet is outdated.
我在互联网上可以找到的所有内容都已过时。
This issue is because both categories and workshops has a column id
此问题是因为类别和研讨会都有列
id
You need to do something like: 您需要执行以下操作:
workshops.joins(:categories).where('category.id = ?', ...)
Notice how it now specifies which id
you're referring to. 请注意,它现在如何指定您要引用的
id
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.