簡體   English   中英

在Rails 3中修改response_to

[英]Modifying respond_to in Rails 3

這是前提:

我有一個名為Rules的模型,該模型具有相應的控制器和視圖。 我希望用戶能夠從其儀表板創建一個新規則,該儀表板具有單獨的視圖和控制器。

儀表板具有三個選項卡,分別稱為“規則”,“規則集”和“游戲”。每個選項卡都有其自己的部分,因此對於“規則”,我使用的是_rules.erb部分,如下所示

<div id="dashboard-rules" class="dashboard-panel ui-nav-panel">
  <%= button_to'Create A Rule', '#', id: "create-rule-btn", class: "btn btn-primary" %>

  <div id="create-rule-form-container">
  </div>

...

</div>

使用jQuery,我正在加載“新規則”頁面的內容,該頁面由“規則”控制器控制,像這樣...

$('#create-rule-btn').click (e) ->
    e.preventDefault()
    $('#create-rule-form-container').load('/rules/new.html .form-horizontal')

這僅從rules / new.html加載表單。 我的問題是,當我單擊“保存規則”按鈕時,它重定向到/ rules URL。 然后顯示錯誤或說“規則保存成功”。 我希望它不要重定向並在儀表板上顯示錯誤...再次,不要重定向到/ rules URL。

這是我的“規則創建”操作,我認為需要對其進行修改,但我不確定如何:

def create
  @rule = Rule.new(params[:rule])

  respond_to do |format|
    if @rule.save
      format.html { redirect_to @rule, notice: 'Rule was successfully created.' }
      format.json { render json: @rule, status: :created, location: @rule }
    else
      format.html { redirect_to :controler => "dashboard"}
      format.json { render json: @rule.errors, status: :unprocessable_entity }
    end
  end
end

我知道我必須弄弄respond_to是如何工作的,我只是不知道如何。

請記住,您需要在create動作中設置在儀表板上設置的所有變量,以使以下各項起作用。 這是因為您要渲染與儀表板相同的模板,因此需要再次設置變量。

if @rule.save
  format.html { redirect_to dashboard_path, notice: 'Rule was successfully created.' }
  format.json { render json: @rule, status: :created, location: @rule }
else
  # initialize the variables needed on the dashboard here
  format.html { render template: 'dashboard/index' }
  format.json { render json: @rule.errors, status: :unprocessable_entity }
end

另一種解決方案是通過ajax提交表單,並在保存規則后刷新頁面。

更新:快速的js解決方案

在創建規則的表單中,添加以下內容

form_for @rule, html: { remote: true } do |f|

這將通過ajax提交表單。 在您的控制器中,在每個format.json之后添加format.js

format.json { ... }
format.js

然后創建一個app/views/rules/create.js.erb (或haml)文件。 在文件中,您可以添加任何所需的js,因此請添加以下內容

<% if @rule.errors.any? %>
  # add js here to append the errors in the page
<% else %>
  window.location.reload
<% end %>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM