I’ve been trying to switch my Orders model to a polymorphic association with my Product and Service models. However, I have a few questions that I haven’t been able to find answers to, even after watching the RailsCast and reading the documentation (so, those suggestions are appreciated, but I need a more concrete answer).
Question:
- Is a polymorphic association the best thing to use in this case? Prior to this, I was using a
Transactionmodel that had multiplebelongs_toassociations and used a custom Parent function to determine which one it was. This was working fine, but someone suggested a polymorphic association may clean things up. - I set up the polymorphic association properly and have been unable to have the
transactable_idandtransactable_typeautomatically populated. The code is below. I have side-stepped this by manually putting them in inside the form, but if anyone knows the proper way to do it, that would be great! - How can I access elements with polymorphic associations? For example, in my Cart object (which
has_manyTransactions and whichTransactionsbelongs_to) I can no longer access things using@cart.transactions.each do |t| ... @t.product.nametype coding.
My model associations look like this:
class Order < ActiveRecord::Base
belongs_to :orderable, :polymorphic => true
end
class Product < ActiveRecord::Base
has_many :orders, :as => :orderable
end
My forms used to look like this:
<% form_for [@orderable, @order] do |f| %>
...
<% end %>
And were rendered like this in my Product Show view:
<%= render 'orders/form' %>
Now, I pass a variable for the product.id in the render partial and use it to populate the transactable_id field. But, I feel like that is very messy.
Again, I have read the tutorials and API docs and have been unable to solve this, so any help would be greatly appreciated!!
Answers to your questions:
*_idand*_typefields depending on associated parent model.Lets say you have Product with many orders in polymorphic association and you want to define which model order belongs to: