2

I am using acts_as_follower in my rails application so that a user can follow a book. My controller is given below. I also have a current_user method.

I want to add an additional field "isFolowing" to the pages response ,This is to check if the current user is following that particular page or not. acts_as_follower gem provides a method user.following?(book) to check if a user is following a particular book.

Please help me to add this additional field "isFollowing" to the response

class BooksController < ApplicationController
   def index
       @books=Book.all
       render json: @books
   end
end
2
  • if you want to have isFollowing in response, render json: {isFollowing: current_user.isFollowing?(book)}. Commented Dec 14, 2014 at 17:06
  • Saravanan, I want to see isFollowing for each of the books in the index action response Commented Dec 14, 2014 at 17:27

1 Answer 1

3

I think, you need to have a method in Book class,

def attributes_with_following_flag(user)
     as_json.merge({is_following: user.is_following(this)})
end

And in controller,

 render json: @books.collect{|b| b.attributes_with_following_flag(current_user)}
Sign up to request clarification or add additional context in comments.

4 Comments

In the controller method, it should be current_user instead of user
thanks a lot for reply @Saravanan .but the user.following?(book) method provided by the gem acts_as_follower is only working if you call from controller and not inside the model. is there anyway we can do this using the "joins" and "includes"
act_as_follower also provides, book.followed_by? method.
Sorry about the confusion @Saravanan your code is right. i wasnt getting current user in my controller. fixed it. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.