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 given @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_toassociations in your model. Like this:You can now use
@customer.category1.name.(edited:
belongs_to, nothas_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_manyinActiveRecord(see the guide: http://guides.rubyonrails.org/association_basics.html#the-has_and_belongs_to_many-association).