擁有客戶和類別表。客戶表中有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?
謝謝。
是的,它是在customer.rb模型中聲明的Customer has_and_belongs_to_many類別。我想將2個類別放入一個客戶記錄中。謝謝。 – user938363
更改關聯後出現錯誤:SQLite3 :: SQLException:no such column:categories.customer_id:SELECT「categories」。* FROM「categories」WHERE「categories」。「customer_id」= 1 LIMIT 1 – user938363
Ah,my bad。這些應該是'belongs_to'關聯。但是,要在模型之間使用'has_many_and_belongs_to',您需要額外的表格。請參閱我在答案中提供的鏈接以獲得一個很好的解釋。 – rdvdijk