0

I am trying to build a index page with a form displayed inside a modal. After the form is submitted with POST action as JS, triggers #create action that responds with redirect_to action #index also as JS, like this

def create
  @output = Output.new(output_params)

  respond_to do |format|
    if @output.save
      format.html { redirect_to @output, notice: 'Output was successfully created.' }
      format.json { render :show, status: :created, location: @output }
      format.js { redirect_to production_line_path @output.machine.production_line, machine_id: @output.machine_id, format: :js }
    else
      format.html { render :new }
      format.json { render json: @output.errors, status: :unprocessable_entity }
    end
  end
end

My problem is that this gives an error with the following description

Security warning: an embedded <script> tag on another site requested protected JavaScript. If you know what you're doing, go ahead and disable forgery protection on this action to permit cross-origin JavaScript embedding.

Completed 422 Unprocessable Entity in 35ms (Views: 27.2ms | ActiveRecord: 1.5ms)

ActionController::InvalidCrossOriginRequest (Security warning: an embedded <script> tag on another site requested protected JavaScript. If you know what you're doing, go ahead and disable forgery protection on this action to permit cross-origin JavaScript embedding.):

I am not sure if I am trying to do this the wrong way. Would I have to change response for JS to not redirect, but rather render from the same controller action #create?

Mr Lister
  • 45,515
  • 15
  • 108
  • 150
adass
  • 333
  • 2
  • 14
  • 1
    Why are you redirecting in `format.js` instead of rendering a JS file? – Raj Mar 17 '17 at 20:55
  • @emaillenin - Not sure, as I wrote I am not sure if this is the correct way to do this. At first I thought that I should have rendering action called from the controller of the model that I want to display. – adass Mar 17 '17 at 21:18

2 Answers2

1

You can either use the built in redirect_to and pass it a path and params, or you can redirect using JS. If you want to redirect do this:

render js: "window.location.pathname = #{production_line_path @output.machine.production_line, machine_id: @output.machine_id}"
ruby_newbie
  • 3,190
  • 3
  • 18
  • 29
0

I think I discovered what was the cause of InvalidCrossOriginRequest error. By mistake my form was sending as JS request without token that normally is automatically added by UJS Rails adapter, but if one uses it.

My form was missing remote: true and instead included format: :js, which made me think I was using UJS Rails adapter and that my POST requests were with needed token for CSRF protection. More at Cross-Site Request Forgery (CSRF)

adass
  • 333
  • 2
  • 14