我有来自另一个非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
表的主键,即 >类别ID
。我正在尝试在这样的控制台中创建一个产品:
c = Category.last
p = c.products.create
我收到一个错误:
ActiveRecord::AssociationTypeMismatch: Category(#29703600) expected, got Fixnum(#17843240)
我尝试了一些其他方法来创建一个产品,我可以在其中传递类别实例,但这会导致其他奇怪的错误。所以现在我只想以这种方式工作。 哪里有问题?
最佳答案
我认为问题在于您有 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">
关于mysql - Rails has_many/belongs_to 自定义数据库 ActiveRecord::AssociationTypeMismatch 得到 Fixnum,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39679549/