sql - has_many join display issue -
newbie rails question... know there's better way this. need understanding why isn't working thought should. i'm doing simple join tables using "has_many" relationship pre-existing database. need keep "non-rails" friendly titles.
here's output <%= room.levels %> seen in browser: [#<level name: "01 - first floor">]
i'd see 01 - first floor without of other information.
i have 2 tables. :rooms , :levels
here's schema 2 tables:
create_table "levels", :primary_key => "id", :force => true |t| t.integer "typeid" t.integer "designoption" t.string "name" t.float "elevation" create_table "rooms", :primary_key => "id", :force => true |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
here's 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
here's snippet app/views/rooms/index.html.erb:
<% @rooms.each |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 sure?' } %></td> </tr>
thanks!
you can this:
<td><%= room.levels.map(&:name).join(', ') %></td>
why code didn't work on first place? because room.levels returns array of level objects. need loop through them each name, , display it.
room.levels # => returns level objects associated room.levels.map(&:name) # => collect each name of level objects (makes array of (string) names) room.levels.map(&:name).join(', ') # => return nice string levels name ", " between each.
Comments
Post a Comment