UserROR
UserROR

Reputation: 240

render json array in rails

My code in controller looks like this:

def dashboard
    @proj_users.each do |us|
      @users<<User.find(us.user_id).email
    end
    render :json=>@users
end

In my view page the javascript looks like this:

$(".clicked").click(function () {
  $.get("/dashboard", {
      clicked_id:this.id,
      user:$("#user").val()
    },
    function (data) {
      $("#all_users").hide();
      $("#proj_users").html(data);
    });
});

@users is an array containing email id. as you can see the data will have @users.

@users will be something like this [email protected],[email protected]

$("#proj_users").html(data); is not getting updated with data..

Kindly help me..

Upvotes: 0

Views: 2748

Answers (2)

ubaid
ubaid

Reputation: 26

two ways

1) solution 1

  @proj_users.each do |us|
     email  = User.find(us.user_id).email + "<br>"
     @users << email
   end
   render :text=>@users

2) solution 2

  @proj_users.each do |us|
     @users<<User.find(us.user_id).email
   end
   render :json=>@users

   in view

   $(".clicked").click(function(){
        $.get("/dashboard",{
        clicked_id:this.id,
        user:$("#user").val()
        },
        function(data)
        {
         $("#all_users").hide();
         $.each(data, function(email){
           $("#proj_users").append(email + "<br>");
         }
        });
   });

Upvotes: 1

HungryCoder
HungryCoder

Reputation: 7616

You can simplify the iteration:

def dashboard
  render :json => @proj_users.map(&:email)
end

Now you need to iterate (using .each() method) on the front end and put this in your html as shown by @ubaid's callback function.

Upvotes: 1

Related Questions