Ruby on rails 如何通过customer表中的两个类别ID之一从类别表中获取类别名称
有客户和类别表。客户表中有category1\u id和category2\u id。如果有@customer,如何通过给定@customer获取类别名称,并将category1_id和category2_id与category表中的id链接 客户模式:Ruby on rails 如何通过customer表中的两个类别ID之一从类别表中获取类别名称,ruby-on-rails,Ruby On Rails,有客户和类别表。客户表中有category1\u id和category2\u id。如果有@customer,如何通过给定@customer获取类别名称,并将category1_id和category2_id与category表中的id链接 客户模式: create_table "customers", :force => true do |t| t.string "name" t.string "short_name" t.string "con
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
谢谢。您的模型中有两个属于关联的单个
。像这样:
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
class客户“Category”,:foreign\u key=>“category1\u id”
属于:category2,:class\u name=>“Category”,:foreign\u key=>“category2\u id”
结束
类类别
您现在可以使用@customer.category1.name
(编辑:属于
,而不是有一个
)
(编辑:添加了:外键
)
然而,我认为您正在为客户和类别之间的“多对多”关系建模,对吗?客户有多个类别,类别可以分配给多个客户。请查看ActiveRecord
中的has_和\u belimited_many
(请参阅指南:)。是的,这是客户在model Customer.rb中声明的has_和\u belimited_many类别。我想把两个类别放在一个客户记录中。谢谢。更改关联后出现错误:SQLite3::SQLException:没有这样的列:categories.customer\u id:从“categories”中选择“categories”。*从“categories”中选择“categories”。“customer\u id”=1限制1Ah,我的坏。这些应该是所属的关联。但是,要在您的模型之间拥有has\u many\u和\u belient\u
,您需要一个额外的表。请参阅我在答案中提供的链接以获得更好的解释。它在将:foreign\u key=>'id'添加到两个belowns\u to:belowns\u to:category1、:class\u name='Category'、:foreign\u key=>'id'后起作用。我发现以下帖子有帮助:。谢谢。发现另一个问题:如果客户同时输入了category1_id和categry2_id,则显示页面将显示不正确的同一类别(似乎从类别表中随机选择一个)。下面是show.html.erb:和中的代码。两行显示的类别相同,但不正确。这是因为两个has\u one关联中的相同外键(id)造成的吗?有什么解决办法吗?谢谢