我不知道问题的标题是否正确。
我有locations
,hardware
和hardware_type
表,但没有嵌套的路线。
我已经建立了关系,以便location
has_manyhardware
和hardware
属于hardware_categories
相互关系。
在我的位置控制器中,我有表演动作
class LocationsController < ApplicationController
before_action :set_location, only: [:show, :edit, :update, :destroy]
# GET /locations
# GET /locations.json
def index
@locations = Location.all
end
# GET /locations/1
# GET /locations/1.json
def show
@hardwares = Hardware.where(:location_id => params[:id])
end
在我的表演页面上
<% @hardwares.each do |hardware| %>
<tr>
<td><%= hardware.name %></td>
<td><%= hardware.asset_tag %></td>
<td><%= hardware.serial_number %></td>
<td><%= hardware.note %></td>
<td><%= hardware.hardware_category_id %></td>
</tr>
<% end %>
这有效,并hardware.hardware_category_id
返回正确的数字。
我想显示的名称hardware_category
,而不是
我以为
<td><%= hardware.hardware_category_id.name %></td>
会工作,但我会得到undefined method 'name' for 1:Fixnum
如何访问这些数据
图式
create_table "hardware_categories", force: true do |t|
t.string "name"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "hardwares", force: true do |t|
t.string "name"
t.string "asset_tag"
t.string "serial_number"
t.text "description"
t.text "note"
t.string "cost"
t.date "purchase_date"
t.date "warranty_end_date"
t.date "eol"
t.datetime "created_at"
t.datetime "updated_at"
t.string "mdl"
t.integer "location_id"
t.integer "hardware_category_id"
t.integer "manufacturer_id"
t.integer "supplier_id"
end
<%= hardware.hardware_category.name %>
是你所需要的。
不需要_id
。关联的名称与您在模型中定义的名称相同。我认为它类似于:
belongs_to :hardware_category
我建议您在尝试做更多的滑轨之前,先阅读本指南。http://guides.rubyonrails.org/association_basics.html
您看到该错误的原因是因为hardware_category_id
正是这样,Integer(FixNum)和FixNum类没有名为的方法/属性name
。
-
Rich Peck编辑
更好的方法是使用.try
评估相应项是否hardware_category
存在...
<%= hardware.hardware_category.try(:name) %>
...如果相应的对象不存在,这将防止任何“找不到”错误。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句