如何通过customer表中的2个类别ID之一从类别表中获取类别名称

时间:2011-09-22 19:13:48

标签: ruby-on-rails

拥有客户和类别表。客户表中有category1_id和category2_id。如果有@customer,如何通过给定@customer获取类别名称并将category1_id和category2_id与类别表中的id相关联?

客户架构:

  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 个答案:

答案 0 :(得分: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

但是,我认为您正在建模客户和类别之间的“多对多”关系,对吧?客户有多个类别,可以将类别分配给多个客户。请查看has_and_belongs_to_many中的ActiveRecord(请参阅指南:http://guides.rubyonrails.org/association_basics.html#the-has_and_belongs_to_many-association)。