2014-11-13 109 views
1

我的新rails 4.1项目具有以下多态关联。rails多态添加<<

class Order < ActiveRecord::Base 
    has_many :line_items, as: :line_itemable 
end 
class LineItem < ActiveRecord::Base 
    belongs_to :line_itemable, polymorphic: true 
end 
class Shipment < ActiveRecord::Base 
    has_many :line_items, as: :line_itemable 
end 

我试图移植一些旧的数据,所以我在我的seeds.rb文件

neworder = Order.create do |order| 
    ... 
end 
neworder.line_items << LineItem.create do |li| 
    ... 
end 

的< <过去一直为我工作。在我的旧制度,我没有出货量类,所以我不得不

class Order < ActiveRecord::Base 
    has_many :line_items 
end 
class LineItem < ActiveRecord::Base 
    belongs_to :order 
end 

和< <只是工作。现在,我已经能够通过使用

neworder = Order.create do |order| 
    ... 
end 
newlineitem = LineItem.create do |li| 
    ... 
end 
newlineitem.update_attribute(:line_itemable, neworder) 

这似乎不像铁轨方式做事情。难道我做错了什么?

回答

0

问题是,在迁移中,您不使用app/models中的类,而是使用移植中的类。请通过rails console检查,的line_itemable_type列的内容。而不是Order你会看到YourMigrationName::Order,这解释了一切。

通常情况下,您的方法是正确的 - 如果需要它的工作,在迁移中定义代码是一种好的做法。只有一个与多态关联的问题:)我认为没有最好的方法来处理它 - 可以手动设置type(这是我会做的),可以手动创建SQL查询(如果您需要创建很多对象,这可能是要走的路,但不应该放在IMO的迁移中)。你可以例如像这样设置类型:

newlineitem = LineItem.create do |li| li.line_itemable_type = 'Order' li.line_itemable_id = neworder.id # other stuff you have end

相关问题