1

A "user" has many "posts". I want to create a counter_cache in "users" that shows how many posts they have.

This is straightforward to do - but I only want posts to be counted in the counter_cache if they are public (i.e post.is_public === true).

How can I create a column in the users table that has their total number of public posts?

class User < ActiveRecord::Base
  // Columns:   id:integer   name:string
  has_many :posts
end

class Post < ActiveRecord::Base
  // Columns:  id:integer   user_id:integer   is_public:boolean   content:text

  belongs_to :user, dependent :destroy, counter_cache: true
end
Don P
  • 60,113
  • 114
  • 300
  • 432
  • possible duplicate of [Counter Cache for a column with conditions?](http://stackoverflow.com/questions/5347323/counter-cache-for-a-column-with-conditions) – Roman Kiselenko Jul 16 '15 at 09:24

2 Answers2

0

if you want to update that counter_cache with update, you could use ActiveRecord callbacks: http://api.rubyonrails.org/classes/ActiveRecord/Callbacks.html. Then you can use conditional either in callback declaration:

before_save :counter_cache, if: proc { |r| r.public }

OR you could have that conditional inside counter_cache method itself, if it knows of record. Otherwise you can just use line above.

Also, it's more idiomatic (and clean) to just use post.is_public, than to compare it stricty against true just like you don't say if a > 3 === true

EdvardM
  • 2,934
  • 1
  • 21
  • 20
0

first you need to make association in the user model and post model

class User < ActiveRecord::Base
 has_many :posts
end

class Post < ActiveRecord::Base
belongs_to :user
end

make column name as counter_cache using following command

 rail g migration add_counter_cache_to_users post:references

now user id is in post table, and you can get the number of post of the user in the controller by first check for public post

 if post.is_public === true
 User_Record = User.first
 id= User_record.id
 user_Post=Post.where(:user_id=>id)
 end

you will get the post of your user on the basis of user id

Ajeet Soni
  • 19
  • 3