首页 > 解决方案 > active admin many to many show index PG::UndefinedColumn: ERROR: column cases.product_id does not exist

问题描述

In my Case model

  has_many :case_products, dependent: :destroy
  has_many :products, through: :case_products

in my Product model

class Product < ActiveRecord::Base
  has_many :cases
end

in CaseProduct

class CaseProduct < ActiveRecord::Base
  belongs_to :case
  belongs_to :product
end

how can I display how many cases I have for each product?

in active admin product.rb

ActiveAdmin.register Product do
  permit_params :id, :name ,case_ids: []
  index do
    column :id
    column :name
    column "case" do |m|
      m.cases.count
    end

    actions

  end
  
  show do
      attributes_table do
        row :id
        row :name
        row :case
        
      end 
  end

end

I got this error

PG::UndefinedColumn: ERROR:  column cases.product_id does not exist
LINE 1: SELECT COUNT(*) FROM "cases" WHERE "cases"."product_id" = $1
                                           ^
: SELECT COUNT(*) FROM "cases" WHERE "cases"."product_id" = $1

标签: ruby-on-railsmany-to-manyactiveadmin

解决方案


You must set associations in Product like your Case model:

class Product < ActiveRecord::Base
  has_many :case_products, dependent: :destroy
  has_many :cases, through: :case_products
end

If you only use has_many :cases, Rails assumes Case model has a product_id column.


推荐阅读