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 documentat开发者_运维知识库ion (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
Transaction
model that had multiplebelongs_to
associations 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_id
andtransactable_type
automatically 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_many
Transactions and whichTransactions
belongs_to
) I can no longer access things using@cart.transactions.each do |t| ... @t.product.name
type 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:
- If your business login implies that multiple models will have related model with the same fields so you should use polymorphic association. (In your case you can use it).
- If set up polymorphic association Rails will automatically handle setting
*_id
and*_type
fields 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:
order = Order.first order.orderable
精彩评论