Search code examples
ruby-on-railsrubyruby-on-rails-4polymorphic-associations

Undefined method `type' for Polymorphic Association


Undefined method `type' for Polymorphic Association.

My Polymorphic association with the models Follow, Dad and Mom gives me an error when writing a method to see if a user is already following one of them.

Here are all of my models and the method following which is the problem.

Models

class User
 has_many :follows

  def following?(followable)
    follows.where(followable_id: followable.id, followable_type: followable.type ).any?
  end
end

class Mom
  has_many :follows, as: :followable, dependent: :destroy
end

class Dad
  has_many :follows, as: :followable, dependent: :destroy
end

Controller

@dad = Dad.find(params[:dad_id])

View

<% unless current_user.following?(@dad) %>
  <%= link_to({ controller: 'follows', action: 'create', id: @dad.id }, { method: :post }) do %>
    Follow
  <% end %>
<% end %>

Error

NoMethodError - undefined method `type' for #<Dad:0xaf63038>:
  activemodel (4.0.2) lib/active_model/attribute_methods.rb:439:in `method_missing'
  activerecord (4.0.2) lib/active_record/attribute_methods.rb:155:in `method_missing'
  app/models/user.rb:17:in `following?'
  .................

This works if I get rid of followable_type but that removes the reason for the method. Why is this happening?


Solution

  • This line is the problem

    follows.where(followable_id: followable.id, followable_type: followable.type ).any?
    

    Replace followable.type with followable.class.name

    type used to be a synonym for class but this was deprecated. Even if it hadn't been deprecated, you need to find records where followable_type is the name of the class, not the class itself.