Rails 3 get Username by ID
How can I get the Username from an ID in Rails 3? In my view I call <%= blog.user_id %> for the ID, but how do I ge开发者_开发百科t the Name there?
The Controller is a scaffold default.
Make sure you define the association in your Blog
model.
belongs_to :user
And then in your view your can use <%= blog.user.name %>
Generally you want to avoid long chains of dots like post.user.name. Try:
class Post < ActiveRecord::Base
belongs_to :user
delegate :name, :to => :user, :prefix => true
end
Then in your views you can call
@post.user_name
to get the users name. I thought I would throw this out there since its good habit I am trying to include in my code as well.
You should use <%= blog.user.name %>
and have defined
belongs_to :user
in your Blog model. You should work with ..._id
on the view-level.
you should learn how to code in Rails, this is a very basic question.
Consider having a look at http://railsforzombies.org
It's a great online tutorial
Try using <%= blog.user.try(:name) %>
精彩评论