Paladini
Paladini

Reputation: 4572

Rails - Model with counter_cache don't work

What's up guys?

I created a migration in my project that add "likes_count" column to Post:

  def self.up
    add_column :posts, :likes_count, :integer, :default => 0
    Post.all().each do |post|
        post.update_attribute(:likes_count, post.likes.count)
          post.save         
    end
  end

  def self.down
    remove_column :posts, :likes_count
  end

Well, it seems worked, but when I try to add "counter_cache" to my Model I'm having troubles. Look:

has_many :likes, :counter_cache => true, :as => :important

Yes, I run the migration without the ":counter_cache => true", only after this migration I added this command. The strange is, if I do something like

has_many :likes, :as => :important,  #:counter_cache => true

my localhost works again. (I only get the error: "We're sorry, but something went wrong.").

Someone know what's going on?

Upvotes: 2

Views: 619

Answers (1)

Paladini
Paladini

Reputation: 4572

I found the problem.

has_many can't have ":counter_cache" parameter, this parameter only works for "belongs_to".

I go to model "like" and inserted the "counter_cache" in "belongs_to":

belongs_to :post, :counter_cache => :likes_count

About the "has_many :likes", I left the way it was:

has_many :likes, :as => :important

Thanks guys...

Upvotes: 3

Related Questions