我希望能够将“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 loos:
[{"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
任何人都知道如何解决这个问题?我会给你一百万美元。
答案 0 :(得分:-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