这就是我想要做的。
当用户单击新便笺时..我希望用户可以开始输入注释时被带到一个页面,并使用AJAX将其保存到服务器上。
问题是,每次页面保存时,它都会生成一个新的注释。
这让我相信,当Rails获得DEF新控制器时,我需要rails首先创建一个新的笔记记录,然后重定向到该新笔记的编辑控制器,在那里用户可以使用AJAX创建/编辑笔记。
有什么想法?谢谢。
发布于 2010-10-26 01:49:40
如果您确实希望使用#new创建便笺并将其保存,那么您可以简单地执行以下操作
def new
@note = Note.create # instead of Note.new
end
然后,Rails将像#edit操作一样显示此注释,因此注释id将位于隐藏字段中。然后,当您发送Ajax调用时,您将调用#edit。如果您希望在关闭javascript时保留#new的行为,那么您可能需要创建一个不同的操作。
def new
@note = Note.new
end
def new_js
@note = Note.create
end
当您加载包含指向new_note的链接的页面时,请包含一些更改指向new_js_note的链接的javascript。所以当JS关闭时,你会得到标准的#new表单。当JS打开时,您得到的表单基本上是在编辑预先存在的空白便笺。
发布于 2010-10-26 01:39:47
我曾经遇到过同样的问题,首先创建备注可能是一个好主意。
另一种方法是将用户发送到新操作。当第一次保存时,您将新对象作为JSON对象发送回来,并用该记录的更新url替换表单的操作,并将表单的方法设置为put。
这样,您就不会在数据库中得到空的记录(对于您的用例,您可能正是想要这样,所以用户可以稍后继续注释。)
这只是我的两个观点。
好的,实现这一点的方法可能如下所示:
表格
<%= form_for resource,
:remote => true,
:html => { 'id' => 'autosave' },
:url => resources_path(:format => :json) do |f| %>
...
<% end %>
应用程序JS
var $form = $('#autosave');
// bind to the first success event from the form
$form.one('ajax:success', function(data, status, xhr) {
// data contains our json object (your note as json)
// now we update the form
$form.attr('action', '/notes/' + data.id);
$form.attr('method', 'put');
$form.attr('data-method', 'put');
});
控制器
class ExampleController
...
def create
#
# respond with the json object if format = json,
# see the form above I'm passing the format with :url parameter in form_for
#
respond_with(resource) do |format|
format.json { render :json => resource }
end
end
end
https://stackoverflow.com/questions/4020031
复制相似问题