使用Rails提交远程表单后,如何将用户重定向到另一个页面?

问题描述:

我正在使用Rails 4.2.3.我想在模式对话框中提交表单,所以我已经像这样设置了表单

I’m using Rails 4.2.3. I want to submit a form in a modal dialog, so I have set up my form like so

<%= form_for @my_object, :remote => true do |f| %>

但是,如果用户成功提交了表单,我想重新加载调用模式对话框的页面,并带有已成功保存"的通知.我无法弄清楚要实现此目的需要在"format.js"中添加什么.到目前为止,这是我的控制器中拥有的……

but if the user submits the form successfully, I would like to reload the page that invoked the modal dialog with a notice of "Saved Successfully." I can’t figure out what I need to put in my "format.js" to make this happen. This is what I have in my controller so far …

  def create
    @my_object = MyObject.new(my_object_params)
    @current_user = User.find(session["user_id"])
    @my_object.user = @current_user
    respond_to do |format|
      if @my_object.save
        format.html { redirect_to controller: "users", action: "index", notice: 'Saved successfully.' }
        format.js   { render action: ‘../users/index’, notice: ‘Saved Successfully’, location: @my_object }
      else
        format.html { render action: "index" }
        format.js   { render json: @my_object.errors, status: :unprocessable_entity }
      end
    end
  end

现在,成功提交会导致500错误,当我尝试执行上述操作时抱怨缺少部分.可以肯定的是,我到底有什么问题.

Right now, a successful submission results in a 500 error complaining about missing partials when I try and execute the above. Pretty sure what I have is wrong anyway.

您可以执行以下操作:

#app/controllers/redirect.rb
...

format.js { render js: "window.location='#{url.to_s}'" }

...

如果您希望将内容分开,只需将format.js放在控制器中,然后在视图中执行javascript重定向(redirect.js.erb)

If you like keeping things separated, just put format.js in your controller and do the javascript redirect in your view (redirect.js.erb)

在两种情况下,只需将flash [:notice]设置为重定向前所需的值即可.

In both cases, just set flash[:notice] to whatever you need before redirecting.