要做到这一点,我发现,并为更全面例如最简单的方法是:
在你看来:
<%= simple_form_for :my_object, url: my_objects_path(format: :json), remote: true do |f| %>
<%= f.error_notification %>
<%= f.input :an_attribute %>
<%= f.submit %>
<% end %>
,并在你的控制器:
def create
@my_object = MyObject.new(my_object_params)
if @my_object.save
respond_to do |format|
format.html { redirect_to @my_object, notice: "Saved" }
format.json { render json: @my_object, location: my_object_url(@object), status: :created }
end
else
respond_to do |format|
format.html { render :edit }
format.json {render json: @my_object, status: :unprocessable_entity }
end
end
end
在Rails 5中,安装了Jbuilder的控制器更容易创建简单的json哈希,但这也应该在那里工作。
谢谢。一个后续问题 - 你是如何设置你的JavaScript回调? – Blake 2013-04-26 15:05:49
我很困惑如何实现这一点。整行代码的外观如何? f.input:my_field:collection => ???? – SteveO7 2014-04-24 15:27:05
对于一些新的浏览器(2015 :)),您需要添加'format :: json'以使表单正常工作,如: '<%= simple_form_for(@object,html:{class:'your_class' ,id:“#new”}},url:your_resource_path(@object,format :: json),remote:true,authenticity_token:true,data:{type:'json'})do | f |%> #Code <%end%>' – Aleks 2015-05-11 13:50:23