bbcbreno bbcbreno - 1 month ago 16
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?

Thanks!

Answer

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 = @hall.pictures.new(:picture=>pic,:title=> "Test")
    if @new_picture.save
        format.json { render json: {files: [@new_picture.to_fileupload_success] }}
    end

###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)

    }
end

HOPE IT HELPS :)

Comments