Search code examples
ruby-on-rails-4polymorphism

Change the polymorphic type column value when doing lookups in Rails


I have a table called comments

class Comments
    belongs_to :commentable, polymorphic: true
end

and a class called Post

class Post
    has_many :comments, as: :commentable
end

the problem is that I recently name spaced the post table. Now it's:

class Nytimes::Post
   has_many :comments, as: :commentable
end

I worry that from here on out that when I do Nytimes::Post.first.comments, it will look for rows in the comments database that have the commentable_type set to Nytimes::Post. Is there any way to override this to look for comments with a commentable_type of Post instead?

I already took care of the writes. I am writing all new comments into the database with commentable_type: "Post". However, it's the retrieval that I'm worried about.


Solution

  • You can override default behaviour of polymorphic association using below:

    class Nytimes::Post
       # has_many :comments, as: :commentable
      has_many :comments, ->(s) { where(comments: { commentable_type: s.class }) }, foreign_key: :commentable_id
    end
    

    And even if your child class is also have namespace i.e. "class Nytimes::Comments" then you could use like below:

    has_many :comments, ->(s) { where(comments: { commentable_type: s.class }) }, foreign_key: :commentable_id, class_name: 'Nytimes::Comments'