0

I have this method in my controller:

# GET /bios/1
# GET /bios/1.json

def show
 if member_session?
   @member = MemberPresenter.new(@bio.member)
   # I need something here to add a flag to the json response to signal this is a member session.
 else
  @member = MemberPresenter.new(@bio.member)
 end
end

I need to modify the json response to return something like:

{ member: @member, member_session: true }

Thanks in advance!

2 Answers 2

1

You can use json param for render functions:

render json: { member: @member, member_session: true }

But it's not the best way to render JSON in rails. I'd recommend you try to use https://github.com/rails-api/active_model_serializers

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

Comments

1

I'm not sure if you specifically want to return json all the time but here's an alternative to rendering other formats as well:

respond_to do |format|
  format.html
  format.json { render json: { member: @member, flag: @member.status } }
end

For small and simple objects, doing this is fine, but if you had to drag the associations along, you have the choice of using a serializer, or you could override the to_json method to something like this.

# member.rb

def as_json(options = {})
  options = options.merge(
    except: [
     :updated_at,
     :created_at,
    ],     
    include: {         # Getting associations here
      address: {
        only: [:street, :zip_code],
        include: {
          neighbors: { only: :name }
          }
        }
      }
   )
  super.as_json(options)
end

And finally within the controller, render json: @member.to_json and it will pull all the associations you want with it. This is the lazy man's way of serializing aka what I do :)

Comments

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.