Rails,在视图中显示模型名称而不是id [英] Rails, displaying model's name in view instead of id

查看:100
本文介绍了Rails,在视图中显示模型名称而不是id的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在此方面,我将非常感谢您的帮助.

I would really appreciate some help on this.

我有以下关系:

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'

我的问题是,能够在挑战模型的视图中显示用户的姓名而不是用户的ID.

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

在控制台中,我可以向@challenge分配一个挑战,然后输入

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'.

我认为与我所做的最正确的事情最接近的是使我的挑战索引视图的相关部分显示为creator,而不是creator_id:

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

推荐答案

我想它一定是在显示对象本身.Challenge.creator是对象,而不是创建者的名称.

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

替换

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

使用

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

这篇关于Rails,在视图中显示模型名称而不是id的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆