1

I have user model and i want the list of users as json and i want the length of name along with the response for each user but i do not how i can do this? I have tried as shown below and it resulted in double render error. If i take the respond_to from the loop then it returns nothing. so please help me.

@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

I want the response to be like

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

2
  • Your desired response doesn't include any length. Commented Jan 31, 2013 at 10:53
  • How can i add methods along with as format.json { render json: all_users.to_json, :methods =>[:pic_url] } ? Commented Jan 31, 2013 at 11:50

1 Answer 1

1

Try:

@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
Sign up to request clarification or add additional context in comments.

5 Comments

size didnt work. so i used count and there are sometimes no name then it displays undefined method `count' for nil:NilClass
user.name.try(:length) should guard you against no-names as well
How can i add methods along with as format.json { render json: all_users.to_json, :methods =>[:pic_url] } ?
but it adds "methods":["pic_url"] along with response and not the url
sorry and i have corrected and as you have told i used pic_url => user.pic_url instead of :methods =>[:pic_url]. Thank you any ways.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.