繁体   English   中英

自定义数据库ActiveRecord :: AssociationTypeMismatch上的Rails has_many / belongs_to得到了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表中,有一个外键category ,该category存储了Category表的主键,即categoryID 我正在尝试在这样的控制台中创建产品:

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

我得到一个错误:

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

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

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

我创建了测试应用

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">

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM