1

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!

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

Great! Thanks! :D Let the json in controller bothers me. I'll move it to model, it will be so beautiful! :D

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.