2015-06-14 68 views
0

我有一個「Establecimientos」(企業)的表單,並且當用戶點擊提交按鈕有一個驗證,可能會導致顯示模式對話框或重定向到「Establecimientos」索引頁面。我一直在嘗試使用和不使用遙控器:在使用html或js調用兩次都出現錯誤的情況下爲true。這是我的控制器(形式不具有遠程:真):從控制器沒有遠程的軌道Ajax調用:true

def create 
@establecimiento = Establecimiento.new(establecimiento_params) 
    if !Establecimiento.exists?(:nit => @establecimiento.nit) 
    respond_to do |format| 
     if @establecimiento.save 
     format.html { redirect_to establecimientos_url, notice: 'El establecimiento se creó exitosamente.'.html_safe } 
     format.json { render :show, status: :created, location: @establecimiento }  
     else 
     format.html { render :new } 
     format.json { render json: @establecimiento.errors, status: :unprocessable_entity } 
     end 
    end 
    else 
    respond_to do |format| 
     format.js { render :action => 'create'} 
     format.html { render :action => 'create', :formats=>[:js]} 
    end 
    end 
    end 

當else塊發生在:格式=> [:JS]不起作用,我的創建的內容。 js.erb顯示在新頁面上,沒有任何呈現爲純文本(控制檯顯示它呈現爲html)。任何幫助表示讚賞

形式部分

<%= bootstrap_form_for(@establecimiento, label_errors: true, layout: :horizontal, label_col: "col-sm-3", control_col: "col-sm-7") do |f| %> 
...content 
<%= f.form_group do %> 
     <%= f.submit %> 
    <% end %> 
     <%= render 'duplicated_modal' %> 
<% end %> 

create.js.erb

<%@duplicated_establishment = Establecimiento.find_by_nit(@establecimiento.nit) %> 
$('.modal-body').html("Ya existe un establecimiento con el mismo NIT (<%= j @duplicated_establishment.nit.to_s %>) ubicado en <%= j @duplicated_establishment.direccion_establecimiento %>, desea crear una nueva sede?"); 
$('.modal-footer').html("<%= j button_to 'Crear nueva sede', new_location_path(@establecimiento), class: "btn btn-primary", "method"=>"post", remote: true%> <button type='button' class='btn btn-default' data-dismiss='modal'>Cancelar</button> ") 
$('#duplicated_conf_modal').modal("show"); 
$('#duplicated_conf_modal').on('shown.bs.modal', function() { 
    $('.first_input').focus() 
}) 

使用遠程:真使所有來電作爲JS但也可以是HTML來電

+0

如果你想用JavaScript做出迴應,你應該使用remote:true。我不熟悉「:formats => [:js]」語法,但它對我來說似乎也是違反直覺的。如果你想要JS,請在JS中提出請求。假設我們要使用remote:true,那麼您能否更新您的問題以顯示帶提交按鈕的.erb模板和create.js.erb響應文件? –

+0

正如我所說的,響應也可能是一個html調用,這就是爲什麼我沒有使用remote:true。我之前使用過它,但問題是當我希望它成爲HTML時,將會有JS調用。我將添加其他文件,謝謝你的回覆 – user2782149

回答

0

如果您想要請求t o讀作format.js,最簡單的方法是在最後打到所需路徑加.js。如establecimientos_path + ".js"。我相信你也可以做establecimientos_path(format: "js")

+0

問題出在'else'部分,我怎麼能在那裏請求動作「創建」? – user2782149

+0

你應該可以只使用'format.js'而不是block,它會適當地呈現'create.js.erb'。 – ptd

+0

沒有responde_to塊?我做了'回覆|格式|' format.js結束'但它會拋出一個UnknownFormat錯誤 – user2782149