【发布时间】:2015-09-30 18:51:39
【问题描述】:
这个问题把我彻底难住了。我还是 RoR 和学习的新手。
我有两张桌子:Countertops 和 Countmaterial。用户将为他们的台面选择所有功能,包括材料类型。材料的选项列在 Countmaterial 表中,并且是从集合中选择的。
我的问题是,一旦做出选择并创建了 Countertop,如何在 Countertops 的索引页面上显示材料类型的名称,而不是 countertype,这是为匹配 Countmaterial 表中的名称而生成的整数?
例如,我希望索引显示“Granite”而不是“1”。 “Granite”列在 Countmaterial 表中,当用户选择“Granite”时,它会在 Countertype 列中将 Countertop 表填充为“1”。大理石是一个“2”等等......
这是我的架构:
create_table "countertops", force: :cascade do |t|
t.string "size"
t.string "color"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "ZipCode"
t.string "countertype"
end
create_table "countmaterials", force: :cascade do |t|
t.string "name"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "countertop_id"
end
我的台面控制器用于索引:
def index
@countertops = Countertop.all
@countertops = Countertop.includes(:countmaterial).all
end
我的索引代码:
<% @countertops.each do |countertop| %>
<tr>
<td><%= countertop.ZipCode %></td>
<td><%= countertop.countmaterial.name %></td>
协会:
class Countertop < ActiveRecord::Base
has_one :countmaterial
end
class Countmaterial < ActiveRecord::Base
belongs_to :countertop
end
大家怎么看?
【问题讨论】:
-
<td><%= countertop.countmaterial.name %></td>不是给你的名字吗? -
不。我收到“nil:NilClass 的未定义方法‘名称’”作为错误。
-
好的,让我们做一些快速调试。请将您的索引更改为
它应该给出一些奇怪的斑点数据,请发布。 其实试试这个我想你可能有一些数据库中没有计数材料的台面实体 inspect.to 行的错误是“范围值错误”
标签: mysql ruby-on-rails associations