Rails 没有响应?

发布于 2024-10-27 01:07:41 字数 829 浏览 1 评论 0原文

我的一个控制器中有一个创建操作,它响应 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

慕烟庭风 2024-11-03 01:07:41

请删除

respond_with(nil, :location => root_path) do |format|
  format.html { redirect_to root_path }
end 

并仅保留此内容

redirect_to root_path

如果您没有任何额外的回复,

remove

respond_with(nil, :location => root_path) do |format|
  format.html { redirect_to root_path }
end 

and leave only this

redirect_to root_path

if you don't any extra respond

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文