【问题标题】:Ruby on Rails - Showing the description instead IDRuby on Rails - 显示描述而不是 ID
【发布时间】:2014-05-06 02:54:09
【问题描述】:

我的项目模型的显示视图中有以下代码

这是一个:

has_one :categorie

查看:

<hr>
<label>Categorie:</label> <%= @item.categorie_id %> </br>
<label>Name: </label> <%= @item.nome_ptbr || @item.nome_en %> </br>
<label>Desc: </label> <%= @item.desc %> </br>
<hr>

但我不想显示“类别:3”,而是显示“类别:乐队”。我得到了这个代码工作*但我不知道是否有更好和正确的方法来做到这一点。

<hr>
<label>Categorie:</label> <%= Categorie.find_by(id: @item.categorie_id).description %> </br>
<label>Name: </label> <%= @item.nome_ptbr || @item.nome_en %> </br>
<label>Desc: </label> <%= @item.desc %> </br>
<hr>

谢谢!

【问题讨论】:

  • 如果您的关联正确,@item.categorie.descricao 应该可以工作。是categorie 还是categoria - 您的代码同时使用两者。
  • 对不起,我将代码翻译到这里,我想我忘记了,无论如何,该代码有效。我担心的是:这是最好的方法吗?
  • Categorie.find_by(id: @item.categorie_id).description
  • 你应该了解模型和关系

标签: ruby-on-rails ruby view-helpers


【解决方案1】:

你可以试试这个方法:

@item.category.try(:description)

这里的描述是你的类别表中的列名

【讨论】:

  • 是的,我错过了研究表之间的关系类型,正确的是“belongs_to :category”而不是“has_one :category”!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多