ruby on rails - How do I change an existing Comment model so it can belong to many different Models? -
in rails app, comment belongs_to page (and stores page_id), while page has_many comments. want comment belong model well, picture. railscasts on polymorphic associations discusses how set commentable intermediary between comment , models belong_to.
however, have existing comment - page setup. how migrate database column , info on new commentable setup nil breaks?
try this:
rename column page_id
commentable_id
, create additional column called commentable_type
, set default: 'page' previous info in table appropriate.
the migrations should be:
1) migration renaming page_id commentable_id
class renamecolumnpageidtocommentableidincomments < activerecord::migration def rename_column :comments, :page_id, :commentable_id end def downwards rename_column :comments, :commentable_id, :page_id end end
2) migration adding commentable_type
class addcolumncommentabletypetocomments< activerecord::migration def add_column :comments, :commentable_type, :string, default: 'page' end def downwards rename_column :comments, :commentable_type, end end
you need alter controller code comments views. hope helps :)
ruby-on-rails ruby-on-rails-4 polymorphic-associations rails-migrations
No comments:
Post a Comment