[英]Rails 3 Polymorphic Associations Question
I've been trying to switch my Orders
model to a polymorphic association with my Product
and Service
models.我一直在尝试将我的
Orders
model 切换为与我的Product
和Service
模型的多态关联。 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).但是,即使在观看 RailsCast 并阅读文档之后,我也有一些问题无法找到答案(因此,这些建议值得赞赏,但我需要更具体的答案)。
Question:问题:
Transaction
model that had multiple belongs_to
associations and used a custom Parent function to determine which one it was.Transaction
model,它有多个belongs_to
关联,并使用了一个自定义 Parent function 来确定它是哪一个。 This was working fine, but someone suggested a polymorphic association may clean things up.transactable_id
and transactable_type
automatically populated.transactable_id
和transactable_type
。 The code is below.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.has_many
Transactions 和 which Transactions
belongs_to
)中,我无法再使用@cart.transactions.each do |t|... @t.product.name
类型编码。 My model associations look like this:我的 model 关联如下所示:
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:我的 forms 曾经看起来像这样:
<% form_for [@orderable, @order] do |f| %>
...
<% end %>
And were rendered like this in my Product
Show view:并在我的
Product
展示视图中呈现如下:
<%= 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.现在,我在渲染部分中为 product.id 传递一个变量,并使用它来填充
transactable_id
字段。 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!!同样,我已经阅读了教程和 API 文档并且无法解决这个问题,所以非常感谢任何帮助!
Answers to your questions:回答您的问题:
*_id
and *_type
fields depending on associated parent model.*_id
和*_type
字段。 Lets say you have Product with many orders in polymorphic association and you want to define which model order belongs to:假设您的 Product 具有多态关联中的许多订单,并且您想定义 model 订单属于哪个:
order = Order.first order.orderable
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.