Justin
Justin

Reputation: 1956

How to Access Related Models in Polymorphic Associations

If I have a polymorphic association, how do I access related methods in my views?

For example, let's say the model associations are:

class Order < ActiveRecord::Base
  belongs_to :orderable, :polymorphic => true
end

class Product < ActiveRecord::Base
  has_many :orders, :as => :orderable
end

And, in the Order view, I tried using:

<%= @order.product.id %>

But, that doesn't work. How do you access related models in the views then?

EDIT: Here's the form I'm using:

<% form_for [@orderable, @order] do |f| %>
  ...
<% end %>

And then, I'm including it in the Product Show view, like this:

<%= render 'orders/form' %>

Upvotes: 1

Views: 1778

Answers (2)

Zabba
Zabba

Reputation: 65467

Try this:

Use the name given to the :as to access the parent:

<%= @order.orderable.id %>

Also, here is some info in the Rails Guides

Upvotes: 5

ardavis
ardavis

Reputation: 9895

Might want to check out the Railscast by Ryan Bates. Should teach you everything you need to know about Polymorphic Associations.

Upvotes: 1

Related Questions