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

标签 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表的主键,即 >类别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/

相关文章:

ruby-on-rails - rails : Logging the entire stack trace of an exception

ruby-on-rails - Rails 中的 PostgreSQL : sorting object by two date attributes in descending order

ruby-on-rails - 在设备中的两个 Web 应用程序之间共享 session

ruby - "__rvm_do_with_env_before"和 "__rvm_after_cd"执行 "cd"时

mysql - 生成一百万个长度为 4 的随机数

ruby-on-rails - 为什么我的模型的唯一性验证规范在应该通过时却失败了?

ruby - 如何使用要在倒排索引中使用的正则表达式匹配 Ruby 中的多行字符串?

c# - EF6 生成查询垃圾 : Eliminate superfluous null checks

mysql - 一般事情开发人员必须知道有 2 年以上的经验?

php - 是否有类似 MailChimp 或 ConstantContact 等邮件列表管理器的免费/开源等效工具?