2012-04-17 82 views
1

我希望能夠「PARAMS」傳遞給「is_following」的方法如下:添加PARAMS渲染方法

 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 

有誰知道如何解決這個問題?我會給你一百萬美元。

+0

語法錯誤告訴你在':is_following'之後缺少逗號。 – jdoe 2012-04-17 18:16:11

回答

-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 
+0

我試過'def friends @user = User.first respond_to do | format | 結束 結束 – 2012-04-17 19:35:58

+0

我的結果是:我的代碼是:認爲我必須得到創造力,並想出辦法。它只是不會工作。 – 2012-04-17 19:36:16

+0

我添加了一個替代方法,而不是做多個數據庫查詢。 – 2012-04-17 19:46:16