开发者

Rails 3 Polymorphic Associations Question

开发者 https://www.devze.com 2023-03-10 02:28 出处:网络
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 wa

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:

  1. Is a polymorphic association the best thing to use in this case? Prior to this, I was using a Transaction model that had multiple belongs_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.
  2. I set up the polymorphic association properly and have been unable to have the transactable_id and transactable_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!
  3. How can I access elements with polymorphic associations? For example, in my Cart object (which has_many Transactions and which Transactions 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:

  1. 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).
  2. If set up polymorphic association Rails will automatically handle setting *_id and *_type fields depending on associated parent model.
  3. 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
    
0

精彩评论

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

关注公众号