1

我希望能够将“params”传递给“is_following”方法,如下所示:

       respond_to |format|
          format.json { render json: @user, :methods => [:is_following params] }
       end

但是,当我在方法名称后面加上“params”时,会引发错误:

syntax error, unexpected tIDENTIFIER, expecting ']'

.

.

当我渲染 JSON(没有 is_following 方法)时,它看起来像这样:

[{"id":81,"image_url":"https://graph.facebook.com/123213123/picture?type=large","full_name":"John Johnson"},{"id":85,"image_url":"https://graph.facebook.com/123123123/picture?type=large","full_name":"Bill Nye"}]

我想添加 is_following 方法,使 JSON 看起来像这样:

[{"id":81,"image_url":"https://graph.facebook.com/123213123/picture?type=large","full_name":"John Johnson",'is_following'=>4},{"id":85,"image_url":"https://graph.facebook.com/123123123/picture?type=large","full_name":"Bill Nye",'is_following'=>9}]

编辑

def friends
  @user = User.first
  respond_to do |format|
    format.json { render json: @user.friends.order("first_name ASC"), :methods => [:is_following], :only => [:id] }
  end
end

模型中的 is_following 方法是:

def is_following params
    return Friendship.where("user_id = ? AND friend_id = ?", params[:user_id], self.id).count
end

有谁知道如何解决这个问题?我会给你一百万美元。

4

1 回答 1

-1

布莱恩,

只需更改此代码:

:methods => [:is_following params]

:is_following => is_following(params)

编辑

无论如何,这是一个更好的方法:

def friends
  @users = User.find_by_sql("SELECT users.*, 
      count(distinct friendships.friend_id) as is_following FROM users
      LEFT JOIN friendships ON users.id = friendships.user_id
      WHERE users.id = " + params[:user_id] + "
      GROUP BY users.id
      ORDER BY users.name ASC")

  respond_to do |format|
    format.json { render json: @users }
  end
end
于 2012-04-17T19:28:12.890 回答