简体   繁体   中英

Redirect to another page in Ruby on Rails

I want to redirect to another page admin_antenna_reader_rfids_path at the end of the create method. I did:

def create
    @antenna_reader_rfid = AntennaReaderRfid.new(antenna_reader_rfid_params)
      if @antenna_reader_rfid.save
        render json: {status: true}
        redirect_to admin_antenna_reader_rfid_path(q@antenna_reader_rfid)
      else
        render json: {errors: @antenna_reader_rfid.errors.full_messages, status: false}
    end
  end

I get an error AbstractController :: DoubleRenderError :

Render and/or redirect were called multiple times in this action. Please note that you may only call render OR redirect, and at most once per action. Also note that neither redirect nor render terminate execution of the action, so if you want to exit an action after redirecting, you need to do something like "redirect_to(...) and return".

How can I solve this?

You have to remove the line render json: {status: true} as currently you're trying to make your controller render a json and redirect to an HTML page at the same time. You have to pick one.

To handle multiple request format, you can use respond_to

if @antenna_reader_rfid.save
  respond_to do |format|
    format.json { render json: { status: true } }
    format.html { redirect_to where_you_want_path }
  end
else
  # same way as above
end

Within the respond_to block, you can render all the request formats as you want, then based on the request header, the controller will choose the corresponding logic to respond to you.

在一个方法中,您不能渲染或返回多次。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM