Rails, displaying model's name in view instead of id

做~自己de王妃 提交于 2020-03-06 06:31:06

问题


I would really appreciate some help on this.

I have relationships such as:

class User < ActiveRecord::Base
  has_many :ideas, :class_name => 'Challenge', :foreign_key => 'creator_id'
  has_many :contributions, :class_name => 'Challenge', :foreign_key => 'contributor_id'

class Challenge < ActiveRecord::Base
  belongs_to :creator, :class_name => 'User'
  belongs_to :contributor, :class_name => 'User'

My problem is being able to display the name rather than the id of a user in the views for the challenge model.

In the console I can assign a challenge to @challenge and then enter

@challenge.creator.name

which returns the name of the creator, perfect. But when I try to put this in my view it returns undefined method 'name'.

I think that the closest to the correct thing that i've done is making the relevant part of my challenges index view say creator, instead of creator_id:

<tr><% @challenges.each do |challenge| %><tr>
<td><%= challenge.creator %></td>

but instead of returning the creator name in the view which is what I want, it returns the following output:

#<User:0x007fe1b81c20b8> 

Could anybody please explain why a field is displayed like this and how I can output the user's name in my view.

My Challenges controller index action is just:

@challenges = Challenge.all

Thank you very much.


回答1:


I guess it must be displaying the object itself. challenge.creator is the object and not the name of the creator.

Replace

<td><%= challenge.creator %></td>

With

<td><%= challenge.creator.try :name %></td>


来源:https://stackoverflow.com/questions/12997010/rails-displaying-models-name-in-view-instead-of-id

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!