2013-01-15 26 views
1

我對rails有點問題。我有一個看起來有點像這樣的遺傳數據庫(hense古怪的列名):與列名同名的Rails關係`

customer 
--------- 
Customer_ID | name | fleet_size | category 
1    'bob'  20   60 

category 
---------- 
Category_ID | Description 
1    'Example Category' 

所以客戶屬於一個類別,一類擁有衆多的客戶。該模型看起來像這樣:

class Category < ActiveRecord::Base 
    set_table_name "category" 

    has_many :customers, :foreign_key => "category" 
end 

class Customer < ActiveRecord::Base 
    set_table_name "customer" 

    belongs_to :category, :foreign_key => "Category_ID" 
end 

因爲在客戶表中的category列的名字,我覺得可能是這意味着我不能在查看通話@customer.category.Description衝突。任何想法解決這個問題?

回答

1

您可以隨時重新命名的關聯關係:

belongs_to :something_else, :class_name => "Category", :foreign_key => "Category_ID" 
1

更改關聯的名稱,並作爲

belongs_to :cust_category, :foreign_key => "Category_ID", :class => 'Category' 

@customer.cust_category.Description 

可能,這將解決您的問題。

+0

太棒了,謝謝!這就是我正在尋找的,它只是返回這個:'nil:NilClass'的undefined方法說明,但我想這是另一個問題 – andy

+0

Woops,顯然我忘記了'除非customer.supplier_index.nil?' – andy

+1

@customer。 cust_category.present?也是一個選項來檢查。 :) –