Bick
Bick

Reputation: 18521

ruby on rails - translate id to name

I have two objects ingredient & origin.
each ingredient has an origin so in the ingredient I have origin_id
the view displays

<p>
  <b>Name:</b>
  <%= @ingredient.name %>
</p>

<p>
  <b>Origin:</b>
  <%= @ingredient.origin_id %>
</p>

I want to display the origin name and not the ID.
How do I bring the name to the display?

EDIT: class ingredient is declared as follows

class Ingredient < ActiveRecord::Base
  has_and_belongs_to_many :recipes
  belongs_to :origin

  attr_accessible :name, :origin_id
end

class origin

class Origin < ActiveRecord::Base
  attr_accessible :name
end

Upvotes: 0

Views: 167

Answers (1)

Baldrick
Baldrick

Reputation: 24340

You have to declare in Ingredientclass:

belongs_to :origin

After that, you can use

<%= @ingredient.origin.name %>

See the Rail Relation Guide (belongs_to and has_one association in your case)

Upvotes: 4

Related Questions