【问题标题】:Rails where query for has_and_belongs_to_manyRails where 查询 has_and_belongs_to_many
【发布时间】:2018-06-29 03:32:25
【问题描述】:

我有研讨会表和类别表。

车间模型:

  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

这个查询的正确方法是什么?我在 Internet 上找到的所有内容都已过时。

【问题讨论】:

    标签: mysql ruby-on-rails postgresql activerecord


    【解决方案1】:

    这个问题是因为分类和工作坊都有一个专栏id

    您需要执行以下操作:

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

    注意它现在如何指定您指的是哪个id

    【讨论】:

    • 太好了,很高兴听到!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-04
    • 1970-01-01
    • 1970-01-01
    • 2012-01-14
    相关资源
    最近更新 更多