Rails 没有响应?
我的一个控制器中有一个创建操作,它响应 ajax 和 html 请求。在创建操作中,我使用 find_or_initialize_by_such_and_such 设置实例变量 (@location)。然后,我测试该位置是否已存在或不使用以下命令:
if @location.id.nil?
@location.save
respond_with(@location, :location => root_path) do |format|
format.html { redirect_to root_path }
end
end
这工作正常,因为基本上部分 (create.js.erb) 将新保存的位置对象附加到列表中。
当用户输入一个已经存在的位置(即有一个 ID)时,就会出现问题。在这种情况下,我不希望将找到的位置附加到列表中,因为这会导致重复(所有位置都已存在)。由于 @location.id.nil?
在这种情况下为 false,因此上述块中的代码显然没有执行,但我很难弄清楚如何处理这种情况。我尝试做类似的事情:
respond_with(nil, :location => root_path) do |format|
format.html { redirect_to root_path }
end
但是 js.erb 文件仍然获取 @location 实例变量并执行将对象添加到列表中的 JavaScript。
因此,解决此问题的最佳方法是什么,以便在 find_or_initialize_by 返回已创建的对象的情况下,响应不会执行 javascript 将此对象附加到列表中?
I have a create action in one of my controllers which responds to ajax and html requests. Inside the create action I set an instance variable (@location) using a find_or_initialize_by_such_and_such. I then test to see if the location already exists or not using this:
if @location.id.nil?
@location.save
respond_with(@location, :location => root_path) do |format|
format.html { redirect_to root_path }
end
end
This works fine since basically the partial (create.js.erb) appends the newly saved location object to a list.
The problem occurs when the user inputs a location which already exists (i.e. has an id). In such a case I do not want the found location to be appended to the list, as it would cause duplication (all the locations are already there). Since @location.id.nil?
is false in that scenario the code within the above block is obviously not executed, but I am having a hard time figuring out how to handle that situation. I tried doing something like:
respond_with(nil, :location => root_path) do |format|
format.html { redirect_to root_path }
end
but the js.erb file still grabs the @location instance variable and executes the javascript that adds the object to the list.
What would be the best way to therefore to work around this, so that in cases where the find_or_initialize_by returns an already created object, the response will not execute the javascript to append this object to a list?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
请删除
并仅保留此内容
如果您没有任何额外的回复,
remove
and leave only this
if you don't any extra respond