0

Sorry if this is totally obvious, but I'm a Rails beginner and am having a really tough time finding the answer to this question.

I'm receiving an AbstractController::DoubleRenderError on my create action, which should simultaneously create a new user (taking in their email address, password, and password confirmation) and create a new profile (which takes in a number of other preferences I ask users to select when creating an account). I basically want to get back the user and profile jsons if they're both successfully created, and receive errors if they're not.

I know the error I'm getting is due to the double "render json" lines I have (one block under the if, one block under the else), but cannot seem to determine how to get these two lines into one.

  def create
    @user = User.new(register_params)
    @profile = Profile.new(profile_params)
    if @user.save && @profile.save
      render json: @user, status: :created, location: @user
      render json: @profile, status: :created, location: @profile
    else
      render json: @user.errors, status: :unprocessable_entity
      render json: @profile.errors, status: :unprocessable_entity
    end
  end

Thank you in advance!

krasten
  • 21
  • 1
  • Welcome to StackOverflow! Sometimes you have to search not by the error that impedes your progress, but by the thing you're actually trying to do. I've linked the relevant question and I'm voting to close yours as it's a duplicate. You may be tempted to remove your question -- don't. It contains another way of getting into the same issue, one that is not given in the linked question. – D-side Aug 04 '15 at 02:14

1 Answers1

0

You can't render twice per controller, if you need to return the result of both models you can write something like this

def create
  @user = User.new(register_params)
  @profile = Profile.new(profile_params)
  if @user.save && @profile.save
    render json: user: @user, profile: @profile, status: :created
  else
    render json: user: @user.errors, profile: @profile.errors, status: :unprocessable_entity
  end
end
rderoldan1
  • 3,517
  • 26
  • 33