2012-01-03 55 views
3

我正在尋找一些示例代碼中顯示驗證錯誤的形式,通過json提交給rails 3.1。表單使用formtastic-bootstrap,並顯示爲一個JQuery對話框。該請求作爲具有JSON數據的xhr請求發送到服務器。該表單是用formtastic創建的,並以模態方式由JQuery顯示。示例應用程序的jquery和rails/formtastic

如果我應該發回JSON中的原始錯誤消息,或者可能將JSON中的HTML應用於顯示驗證錯誤的div,這並不明顯。

回答

1

我只使用jQuery的ujs功能並返回完整的html。

下面是一個例子:

視圖/資源/ _form.html.erb

<%= semantic_form_for @resource, remote: true do |f| %> 
    <%= f.input :title %> 
    <%= f.input :description %> 
    <%= f.submit %> 
<% end %> 

視圖/資源/ new.html.erb

<h1>Create a New Resource</h1> 
<%= render 'form' %> 

controllers/resources_controller.rb

class ResourceController < ApplicationController 
    def new 
    @resource = Resource.new 
    end 

    def create 
    @resource = Resource.new(params[:resource]) 
    if @resource.save 
     render js: "$('.my-modal').modal('close')" 
    else 
     render js: "$('.my-modal #new-resource-form').replaceWith('#{j render('form')}')" 
    end 
    end 
end 
+0

這很酷。我會一直創建一個js.erb文件。很高興知道內聯技術。 – justingordon 2013-01-12 08:34:19