logesh
logesh

Reputation: 2662

how can i include a variable at each array in rails?

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"}}]

Upvotes: 1

Views: 72

Answers (1)

shweta
shweta

Reputation: 8169

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

Upvotes: 1

Related Questions