akmur
akmur

Reputation: 1635

Rails - how to display a name related to an ID

i have a (hopefully) simple question that might have been answered before.. i just couldnt find it... well, here we go, should be easy enough.

I have this schema

create_table "items", :force => true do |t|
t.text     "description"
t.string   "priority"
t.date     "date"
t.time     "time"
t.datetime "created_at"
t.datetime "updated_at"
t.boolean  "done"
t.integer  "user_id"
end

create_table "users", :force => true do |t|
t.string   "name"
t.datetime "created_at"
t.datetime "updated_at"
end

And I have this in my form for adding a new item:

<%= collection_select(:item, :user_id, User.all, :id, :name) %>

Now, it works, data is saved correctly (I already set up the proper correlations). What i want though, is to display in the items index, the name of the person the item is assigned to, instead of just an ID number.

In items/index I have:

<td><%= item.user_id. %></td>

but i rather want something like

item.user.name

only, it won't work - I guess I need some action in my controller. Can you help me please? :)

EDIT here is some more details: My models:

class User < ActiveRecord::Base
has_many :items
end

class Item < ActiveRecord::Base
belongs_to :user
end

Upvotes: 0

Views: 137

Answers (1)

David Grayson
David Grayson

Reputation: 87406

Add this to your Items class:

class Items < ActiveRecord::Base
  belongs_to :user
end

Then item.user.name should work.

Upvotes: 1

Related Questions