rails:如何在json响应中包含其他字段

时间:2014-12-14 16:58:48

标签: ruby-on-rails ruby ruby-on-rails-3 join activerecord

我在rails应用程序中使用acts_as_follower,以便用户可以关注书籍。我的控制器如下。我也有一个current_user方法。

我想在页面响应中添加一个额外的字段“isFolowing”,这是为了检查当前用户是否正在关注该特定页面。 acts_as_follower gem提供了一个方法user.following?(book)来检查用户是否正在关注某本书。

请帮我将此附加字段“isFollowing”添加到回复

class BooksController < ApplicationController
   def index
       @books=Book.all
       render json: @books
   end
end

1 个答案:

答案 0 :(得分:2)

我认为,你需要在Book类中有一个方法,

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)}