2016-09-24 74 views
0

我有另一個非rails項目的數據庫,所以我不得不處理unordinary列名。我有模型類別:在自定義數據庫上的Rails has_many/belongs_to ActiveRecord :: AssociationTypeMismatch得到了Fixnum

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的表,這是categoryID 。我想在這樣的一個控制檯創建一個產品:

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

我得到一個錯誤:

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

我嘗試了一些其他的方式來創造一個產品,我可以通過分類實例但它會導致其他奇怪的錯誤。所以現在我只想要這種方式工作。 問題在哪裏?

+0

,只是'c.products'作品? – Aleksey

+0

是的,它的工作原理。但我不得不從種子創建一個產品,甚至在那裏它不接受類別字段的整數,它只接受類別實例 Product.create({category:c}) –

+1

我認爲這是因爲你有DB列'類別「和具有相同名稱的關聯。 – Aleksey

回答

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

它完全有效,非常感謝! –

+0

根本不是,但是對於那些列名非常奇怪的傢伙來說,這是一個榮譽的問題=) – Aleksey

+0

那些傢伙不再在那裏工作。無論如何,他們的網站是用php和wordpress製作的,所以我不認爲像這樣的列名對他們來說很陌生 –

相關問題