Parry Parry - 10 months ago 42
Ruby Question

How to query a different table and show values related to foreign key in Rails Application instead of hex values

I have two models in my rails application.

class Item < ApplicationRecord
belongs_to :item_type


class ItemType < ApplicationRecord
validates_presence_of :item_type, :message=>"name cannot be blank!"
has_many :items

While adding an item, I am getting the users to select the item type using a drop down selector.

<%= form_for(item) do |f| %>
<% if item.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(item.errors.count, "error") %> prohibited this item from being saved:</h2>

<% item.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
<% end %>

<div class="field">
<%= f.label :item %>
<%= f.text_field :item %>

<div class="field">
<%= f.label :item_type_id %>
<%= f.collection_select :item_type_id, ItemType.all, :id, :item_type %>

<div class="actions">
<%= f.submit %>
<% end %>

The view for index page of item is like this.

<p id="notice"><%= notice %></p>


<th>Item type</th>
<th colspan="3"></th>

<% @items.each do |item| %>
<td><%= item.item %></td>
<td><%= item.item_type %></td>
<td><%= link_to 'Show', item %></td>
<td><%= link_to 'Edit', edit_item_path(item) %></td>
<td><%= link_to 'Destroy', item, method: :delete, data: { confirm: 'Are you sure?' } %></td>
<% end %>


<%= link_to 'New Item', new_item_path %>
<%= link_to "Home", '/' %>

Now in this index page, I see the hex value of Item Type as shown in the image.


Instead of this hex code, I would like to pull the item_type (string) from the item_types table and display it in the index page for items.

Answer Source

Use <td><%= item.item_type.item_type %></td>. It looks weired but you will have to use this way since item.item_type shows the ItemType object and I think you want the actual item_type value from ItemType object so you will have to put the attribute name again i.e item.item_type.item_type.

To avoid confusion, you can rename the item_type column to something else(not to only type, that is reserved fro STI only.). Hope it helps.