开发者

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开发者_JAVA百科

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' %>


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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜