开发者

how to fetch category name from category table by one of 2 category ids in customer table

Having customer and category table. There are category1_id and category2_id in customer table. If having @customer, how to fetch the category name by gi开发者_JAVA技巧ven @customer and linking the category1_id and category2_id with the id in category table?

customer schema:

  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

category schema:

  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

In routes.rb file

  resources :customers do
    resources :categories
  end

Given @customer, how to fetch category name, like @cusotmer(category1_id).category.name?

Thanks.


You have two single belongs_to associations in your model. Like this:

    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

You can now use @customer.category1.name.

(edited: belongs_to, not has_one) (edited: added :foreign_key)

However, I think you are modeling a "many-to-many" relationship between customers and categories, right? Customers have multiple categories, and categories can be assigned to multiple customers. Take a look at has_and_belongs_to_many in ActiveRecord (see the guide: http://guides.rubyonrails.org/association_basics.html#the-has_and_belongs_to_many-association).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜