Search code examples
ruby-on-railsactiverecordmany-to-manyhas-many

Rails has_many :through "ERROR - column products.category does not exist"


Trying to resolve my issue, I've found a lot of common confusion surrounding has_many :through and has_and_belongs_to_many (which I'd like to avoid using). Reading through most of that on Stackoverflow makes me think I've set this up correctly:

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

And my migration. I've seen several ways to go about this, and this way seems valid:

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

And in my categories controller, I'm trying to create an ActiveRecord relation through this association:

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

If I simply do @category.products, everything is fine, and I get an array/collection of a number of products included in that category. But I don't want an array. If I try to use where I get this error:

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

Is there a more complex joins statement I should make to get an AR relation of products in a certain category? I'm sure it should work the way I'm attempting but obviously I've gone wrong somewhere.

Update

I've been able to create a relation with this code:

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

Is this the correct way to do this? I still feel like my "column does not exist error" indicates I've done something incorrectly elsewhere and need to identify it.


Solution

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

    The error indicates that the column category doesn't exist in the products table. This is because you are trying to query with an non-existed column here in this line @products = Product.where(:category => @category)

    Also, I would simply write it as @products = @category.products, but as you want the result as AR relation your current approach(@products = Product.where(:id => @category.product_ids)) looks fine to me.