导轨has_many:通过"ERROR - column products.category does not exist"



试图解决我的问题,我发现了很多关于has_many :throughhas_and_belongs_to_many的常见混淆(我想避免使用)。在Stackoverflow上阅读了大部分内容,使我认为我已经正确设置了:

class Product < ActiveRecord::Base
  has_many :categorizations
  has_many :categories, :through => :categorizations
end
class Category < ActiveRecord::Base
  has_many :categorizations
  has_many :products, :through => :categorizations
end
class Categorization < ActiveRecord::Base
  belongs_to :product
  belongs_to :category
end

和我的迁移。我已经见过好几种方法,这种方法似乎是有效的:

class CreateCategorizations < ActiveRecord::Migration
  def change
    create_table :categorizations, :id => false do |t|
      t.references :product
      t.references :category
    end
    add_index :categorizations, [:category_id, :product_id], :unique => true
  end
end

在我的类别控制器中,我试图通过这个关联创建一个ActiveRecord关系:

class CategoriesController < ApplicationController
  def show
    @category = Category.find(params[:id])
    @products = Product.where(:category => @category)
  end
end

如果我只是做@category.products,一切都很好,我得到了一个包含在该类别中的许多产品的数组/集合。但我不想要一个数组。如果我尝试使用where,我得到这个错误:

ActiveRecord::StatementInvalid - PG::UndefinedColumn: ERROR:  column products.category does not exist

是否有一个更复杂的连接语句,我应该使在某一类别的产品的AR关系?我确信它应该像我所尝试的那样工作,但显然我在某个地方出错了。

<标题> 更新

我已经能够用这段代码创建一个关系:

@products = Product.where(:id => @category.product_ids)

这样做正确吗?我仍然觉得我的"列不存在错误"表明我在其他地方做错了什么,需要识别它

ActiveRecord::StatementInvalid - PG::UndefinedColumn: ERROR: column产品。目录不存在

错误表明列类别在products表中不存在。这是因为您正在尝试查询这一行中不存在的列@products = Product.where(:category => @category)

另外,我会简单地将其写为@products = @category.products,但是当您希望结果为AR关系时,您当前的方法(@products = Product.where(:id => @category.product_ids))对我来说看起来很好。

最新更新