bbcbreno bbcbreno - 1 year ago 156
JSON Question

Render Json with methods and several objects

On Rails I can render some json with extra method like this:

render json: {
user: user
}, methods: :photo_url

It work's fine! But, I need put more objects in this json that don't has the photo_url method.

render json: {
brand: brand,
user: user
}, methods: :photo_url

I got this error:

undefined method 'photo_url' for brand

So, How can I insert this method only to user object?


Answer Source

instead of making json in controller,you should try the same in a model..Check a sample code below,i have added a simple url...with routes too. Also make use of url_helpers to add routes in json file.

###a part of create action in controller=>USERS_CONTROLLER.RB
    ##code is wrapped in respond_to block
    @new_picture =>pic,:title=> "Test")
        format.json { render json: {files: [@new_picture.to_fileupload_success] }}

###return json from model=>USER.RB/PICTURE.RB
def to_fileupload_success
      "name" => read_attribute(:picture_file_name),
      "size" => read_attribute(:picture_file_size),
      "url" =>  picture.expiring_url.to_s,
      "thumbnailUrl" => picture.expiring_url.to_s,
      "success" => "Picture uploaded",
      "showeUrl" => Rails.application.routes.url_helpers.user_picture_path(self)



Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download