1

我有用户模型,我想要用户列表作为 json,我想要length of name每个用户的响应,但我不知道我该怎么做?我已经尝试如下所示,它导致了double render错误。如果我从循环中获取 response_to,那么它什么也不返回。所以请帮助我。

@users = User.all
   @users.each do |user|
      length = user.name.count
        respond_to do |format|
          format.json { render json: @users.to_json(:include => [:length]) }
        end
      end

我希望回复像

[{"user":{"name":asgd,"id":1,"length":"4"}},{"user":{"name":asdfg,"id":2,"length" :"5"}}]

4

1 回答 1

1

尝试:

@users = User.all
all_users = Array.new
@users.each do |user|
  all_users << {"id" => user.id, "name" => user.name,"length" => user.name.size}
end
respond_to do |format|
  format.json { render json: all_users.to_json }
end
于 2013-01-31T11:03:02.270 回答