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

时间:2016-09-24 18:17:37

标签: mysql ruby-on-rails ruby activerecord associations

我有来自另一个非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表的主键categoryIDc = Category.last p = c.products.create 1}}。我试图在控制台中创建一个产品:

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

我收到错误:

{{1}}

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

1 个答案:

答案 0 :(得分:1)

我认为问题在于您有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">