Robert
Robert

Reputation: 545

Ruby - access parent property from child - one to many relation

class PriceList < ActiveRecord::Base
  has_many :prices, :dependent => :destroy
end

and Price:

class Price < ActiveRecord::Base
  belongs_to :price_list
  belongs_to :material
  belongs_to :unit
end

Now in price_list index I want to show Price list name instead of id:

<tbody>
    <% @prices.each do |price| %>
      <tr>
        <td><%= price.price_list.price_list_short_name %></td>
        <td><%= price.materials_id %></td>
        <td><%= price.units_id %></td>
        <td><%= link_to 'Show', price %></td>
        <td><%= link_to 'Edit', edit_price_path(price) %></td>
        <td><%= link_to 'Destroy', price, method: :delete, data: { confirm: 'Are you sure?' } %></td>
      </tr>
    <% end %>
  </tbody>

What I am doing wrong that price.price_list.price_list_short_name does not work?

Upvotes: 0

Views: 78

Answers (2)

Robert
Robert

Reputation: 545

I was missing proper references. Adding to migration file:

class AddReferencesToPrices < ActiveRecord::Migration
  def change
    remove_column :prices, :price_list_id
    remove_column :prices, :materials_id
    remove_column :prices, :units_id
    add_reference :prices, :price_list, :index => true
    add_reference :prices, :material, :index => true
    add_reference :prices, :unit, :index => true
  end
end

solved problem.

Upvotes: 0

Marek Lipka
Marek Lipka

Reputation: 51191

At least one of your Price records doesn't have its price_list associated. The solution depends on your intentions. If you want to force all prices to have price_list, you can add validation:

class Price < ActiveRecord::Base
  validates :price_list, presence: true
  # ...
end

If you want to allow price_list-less prices, you could make use of try method, which will fix the error in view:

price.price_list.try(:price_list_short_name)

BTW, naming your column price_list_short_name in price_lists table is a bit redundant.

Upvotes: 1

Related Questions