polymorphism - rails polymorphic add using << -
my new rails 4.1 project has next polymorphic associations.
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
i trying migrate old info have in seeds.rb file
neworder = order.create |order| ... end neworder.line_items << lineitem.create |li| ... end
the << has worked me in past. in old scheme didn't have shipments class had
class order < activerecord::base has_many :line_items end class lineitem < activerecord::base belongs_to :order end
and << worked. now, have been able create migration work using
neworder = order.create |order| ... end newlineitem = lineitem.create |li| ... end newlineitem.update_attribute(:line_itemable, neworder)
this not seem rails way things. doing wrong?
the problem in migration not utilize class app/models, 1 within migration. check via rails console
what's in line_itemable_type
column chosen lineitem
. instead of order
see yourmigrationname::order
, explains everything.
in general approach right though - practice define code in migration if requires work. there 1 gotcha polymorphic association :) think there no 'best' way deal - 1 can set type
manually (this have done), 1 can craft sql query manually (if need create lot of objects way go, shouldn't placed in migration imo). can illustration set type this:
newlineitem = lineitem.create |li| li.line_itemable_type = 'order' li.line_itemable_id = neworder.id # other stuff have end
polymorphism ruby-on-rails-4.1
No comments:
Post a Comment