Model associations are one of the things that every new Ruby on Rails developer must understand in order to effectively use the framework. The concept behind these relationships is rather simple, and most people have little trouble grasping it once introduced.
In polymorphic associations, a model can fit into more than one model, on a single association. Like just about everything else in the Ruby on Rails world, there is a ‘Rails way’ to do polymorphic associations. This involves leveraging the support that is built in to Rails’ standard ORM, Active Record. You set up a polymorphic association in very much the same way that you would a typical has_many.
Here are the steps to implement the polymorphic association between these three models.In polymorphic associations, a model can fit into more than one model, on a single association. Like just about everything else in the Ruby on Rails world, there is a ‘Rails way’ to do polymorphic associations. This involves leveraging the support that is built in to Rails’ standard ORM, Active Record. You set up a polymorphic association in very much the same way that you would a typical has_many.
belongs_to :commentable, polymorphic: true #...
class Profile < ActiveRecord::Base
class CreateComments < ActiveRecord::Migration
def change
t.references :commentable, polymorphic: true #...
end
end
end
Here you can see that all we’re really doing is passing a couple of parameters to the :has_many and :belongs_to methods. The migration will generate two columns on the Comments table, ‘commentable_id’ and ‘commentable_type’. Behind the scenes, Active Record will wire up all of the helper methods that you’re used to using with normal associations. Now the comment model will work as a polymorphic association between Post and Profile model.
No comments:
Post a Comment