Home > Software engineering >  Need help returning expected JSON output
Need help returning expected JSON output

Time:07-11

I am trying to append authorIds into the post map. I am not sure if this is possible to do since I have close to no experience with Ruby. I have tried using multiple methods on the post map, such as merge, store, and others, however, nothing seems to work. I would appreciate any help I can receive, Thank you in advance!

def update
  post = current_user.posts.find_by(id: params[:id])
  # postMap = {post: post}
  # post.merge!("authorIds": params[:authorIds])
  # newPost = post.merge!('authorIds', params[:authorIds]
  if post.update(post_params)
    render json: {post: post}, status: :ok
  else
    render json: {error: post.errors}, status: :unprocessable_entity
  end
end

Route function Image to test case

CodePudding user response:

For the most part of your update method, you deal with an instance of Post and not with a hash object. When you just want to return a value in the response then you need to add it to the object that will be returned as close to the end as possible.

Because the translation from an instance of Post to the returned JSON structure is done automatically you need to break those automatical steps and there add your new value.

def update
  post = current_user.posts.find_by(id: params[:id])
  if post.update(post_params)                       # `post` is an instance of `Post`
    post_hash = post.as_json                        # translate into a Ruby hash
    post_hash.merge!(authorIds: params[:authorIds]) # merge the additional value
    render json: { post: post_hash }, status: :ok   # return the modified hash
  else
    render json: { error: post.errors }, status: :unprocessable_entity
  end
end

Notes: When you have a line like json: { post: post } then Ruby on Rails will first call as_json on post which will translate the instance of Post into a Ruby hash representation of a Post, then Rails will dump that hash into a JSON string. By breaking into those steps we are able to inject additional values into the hash.

Btw: the authorIds key in the params and in the returned hash is not following Ruby conventions and might confuse other developers working on the same project in the future. I suggest naming it author_ids instead.

  • Related