mercredi 30 mars 2016

Ruby on Rails: Polymorphic Association Confusion

I am contributing one of the ruby on rails application over GitHub where I faced the following scenario:

I am having following models which I want to convert to make polymorphic:

class Comment < ActiveRecord::Base
  belongs_to :team
  belongs_to :user
  belongs_to :application
  belongs_to :project
end

class Team < ActiveRecord::Base
  has_many :comments
end

class Project < ActiveRecord::Base
  has_many :comments
end

class User < ActiveRecord::Base
end

class Application < Rails::Application
end

I made following changes to make it polymorphic:

Perform database change to removed team_id, project_id, application_id and user_id and added commentable_id and commentable_type to comments table.

Modifications in models:

class Comment < ActiveRecord::Base
  belongs_to :commentable, polymorphic: true
end

class Team < ActiveRecord::Base
  has_many :comments, as: :commentable
end

class Project < ActiveRecord::Base
  has_many :comments, as: :commentable
end

As described within rails guides.

I am confused to change in following models:

class User < ActiveRecord::Base
end

class Application < ActiveRecord::Base
end

Should I need following changes in User and Application model?

class User < ActiveRecord::Base
  has_many :comments, as: :commentable
end

class Application < ActiveRecord::Base
  has_many :comments, as: :commentable
end

Thanks in Advance!

Aucun commentaire:

Enregistrer un commentaire