Rails has_many/belongs_to 在自定义数据库上 ActiveRecord::AssociationTypeMismatch 得到 Fixnum

Rails has_many/belongs_to on custom database ActiveRecord::AssociationTypeMismatch got Fixnum

我有另一个非 rails 项目的数据库,所以我必须处理非常规的列名。我有模型类别:

self.primary_key = "categoryID"
has_many :products, foreign_key: "category", primary_key: "categoryID"

和型号产品:

self.primary_key = "productID"
belongs_to :category, foreign_key: "category", primary_key: "categoryID"

Product 的 table 中有一个外键 category 存储 Category 的 table 的主键,即 categoryID。我正在尝试在这样的控制台中创建产品:

c = Category.last
p = c.products.create

我得到一个错误:

ActiveRecord::AssociationTypeMismatch: Category(#29703600) expected, got Fixnum(#17843240)

我尝试了一些其他方法来创建一个产品,我可以在那里传递 Category 实例,但它会导致其他奇怪的错误。所以现在我只想以这种方式工作。 哪里有问题?

我认为问题在于您有 category 列(因此 Rails 为它创建了 category 方法)和 category 具有相同名称的关联。
你可以给association取个别的名字

我创建了测试应用程序

class CreateProducts < ActiveRecord::Migration
  def change
    create_table :products, id: false do |t|
      t.integer :productID
      t.integer :category
      t.string  :title
    end
  end
end

class CreateCategories < ActiveRecord::Migration
  def change
    create_table :categories, id: false do |t|
      t.integer :categoryID
      t.string  :title
    end
  end
end

class Product < ActiveRecord::Base
  self.primary_key = :productID

  belongs_to :my_category, class_name: 'Category', foreign_key: :category
end

class Category < ActiveRecord::Base
  self.primary_key = :categoryID

  has_many :products, foreign_key: :category
end

这样下面的代码似乎可以正常工作

c = Category.create categoryID: 1, title: 'First category'
c.products # => []
c.products.create productID: 1, title: 'First product' 
c.products.create productID: 2, title: 'Second product'
c.products # => #<ActiveRecord::Associations::CollectionProxy [#<Product productID: 1, category: 1, title: "First product">, #<Product productID: 2, category: 1, title: "Second product">]>

p = Product.first
p.category # => 1
p.my_category # => #<Category categoryID: 1, title: "First category">