2011-09-22 81 views
0

擁有客戶和類別表。客戶表中有category1_id和category2_id。如果擁有@customer,如何通過給定@customer獲取類別名稱,並將category1_id和category2_id與類別表中的id鏈接起來?如何通過客戶表中的2個類別標識之一獲取類別表中的類別名稱

客戶概要:

create_table "customers", :force => true do |t| 
    t.string "name" 
    t.string "short_name" 
    t.string "contact" 
    t.string "address" 
    t.string "country" 
    t.string "phone" 
    t.string "fax" 
    t.string "email" 
    t.string "cell" 
    t.integer "sales_id" 
    t.string "web" 
    t.integer "category1_id" 
    t.integer "category2_id" 
    t.boolean "active",   :default => true 
    t.string "biz_status" 
    t.integer "input_by_id" 
    t.string "quality_system" 
    t.string "employee_num" 
    t.string "revenue" 
    t.text  "note" 
    t.integer "user_id" 
    t.datetime "created_at" 
    t.datetime "updated_at" 
    end 

類模式:

create_table "categories", :force => true do |t| 
    t.string "name" 
    t.string "description" 
    t.boolean "active",  :default => true 
    t.datetime "created_at" 
    t.datetime "updated_at" 
    end 

在routes.rb中文件

resources :customers do 
    resources :categories 
    end 

鑑於@customer,如何獲取類別名稱,比如@cusotmer( category1_id).category.name?

謝謝。

回答

1

您的模型中有兩個單獨的belongs_to關聯。像這樣:

class Customer < ActiveRecord::Base 
     belongs_to :category1, :class_name => "Category", :foreign_key => "category1_id" 
     belongs_to :category2, :class_name => "Category", :foreign_key => "category2_id" 
    end 

    class Category < ActiveRecord::Base 
    end 

您現在可以使用@customer.category1.name

(編輯:belongs_to,不has_one) (編輯:添加:foreign_key

不過,我覺得你是一個建模「許多一對多」的客戶和類別之間的關係,對不對?客戶有多個類別,而類別可以分配給多個客戶。看看 ActiveRecord(參見指南:http://guides.rubyonrails.org/association_basics.html#the-has_and_belongs_to_many-association)。

+0

是的,它是在customer.rb模型中聲明的Customer has_and_belongs_to_many類別。我想將2個類別放入一個客戶記錄中。謝謝。 – user938363

+0

更改關聯後出現錯誤:SQLite3 :: SQLException:no such column:categories.customer_id:SELECT「categories」。* FROM「categories」WHERE「categories」。「customer_id」= 1 LIMIT 1 – user938363

+0

Ah,my bad。這些應該是'belongs_to'關聯。但是,要在模型之間使用'has_many_and_belongs_to',您需要額外的表格。請參閱我在答案中提供的鏈接以獲得一個很好的解釋。 – rdvdijk

相關問題