Newbie Rails问题......我知道有更好的方法来做到这一点。我需要帮助理解为什么这不像我认为的那样工作。 我正在使用与现有数据库的“has_many”关系进行简单的连接表。我需要保持“非铁路”友好的头衔。
这是输出&lt;%= room.levels%&gt;如浏览器中所示:[#<Level Name: "01 - FIRST FLOOR">]
我想在没有所有其他信息的情况下只看到01 - FIRST FLOOR。
我有两张桌子。 :房间和:水平
这是两个表的架构:
create_table "levels", :primary_key => "Id", :force => true do |t|
t.integer "TypeId"
t.integer "DesignOption"
t.string "Name"
t.float "Elevation"
create_table "rooms", :primary_key => "Id", :force => true do |t|
t.integer "DesignOption"
t.integer "PhaseId"
t.string "Comments"
t.float "Volume"
t.float "Perimeter"
t.integer "Level"
t.string "Occupancy"
t.float "Area"
t.string "Number"
t.string "Name"
end
add_index "rooms", ["Id"], :name => "Id", :unique => true
这是app / model / room.rb:
class Room < ActiveRecord::Base
attr_accessible :Area, :Level, :Name, :Number, :Perimeter, :PhaseId, :Elevation
has_many :levels, :primary_key => 'Level', :foreign_key => 'Id', :select => 'Name' set_primary_key :Id
end
以下是app / views / rooms / index.html.erb的摘录:
<% @rooms.each do |room| %>
<tr>
<td><%= room.Name %></td>
<td><%= room.Number %></td>
<td><%= room.PhaseId %></td>
<td><%= room.levels %></td>
<td><%= link_to 'Show', room %></td>
<td><%= link_to 'Edit', edit_room_path(room) %></td>
<td><%= link_to 'Destroy', room, method: :delete, data: { confirm: 'Are you sure?' } %></td>
</tr>
谢谢!
答案 0 :(得分:1)
你可以这样做:
<td><%= room.levels.map(&:Name).join(', ') %></td>
为什么您的代码无法正常工作?因为room.levels返回一个Level对象数组。您需要遍历它们以获取每个名称,然后显示它。
room.levels
# => returns all the level objects associated
room.levels.map(&:Name)
# => collect each name of the level objects (makes an array of (String) names)
room.levels.map(&:Name).join(', ')
# => Return a nice String with all the levels name with ", " between each.
答案 1 :(得分:0)
因为levels
会为您提供回收。你需要迭代room.levels
并在那里获得元素
答案 2 :(得分:0)
对于你当前的Schema,Room belongs_to级别,房间没有办法可以有多个级别(除非只有那两个表)
create_table "rooms", :primary_key => "Id", :force => true do |t|
...
t.integer "Level" # One-to-One relation
所以,你需要的是:
# Model
class Room < ActiveRecord::Base
attr_accessible :Area, :Level, :Name, :Number, :Perimeter, :PhaseId, :Elevation
belongs_to :level, :primary_key => 'Level', :foreign_key => 'Id', :select => 'Name'
end
# View
<td><%= room.level.name %></td>