我有一个 Rails 应用程序似乎没有触发预期命名的 .js.erb 文件,所以我想覆盖默认行为,但我不确定如何。
详情:
这是一个 Rails 3 应用程序,它呈现一个带有 AJAX 调用的 button_to 以在后端切换某物的状态,然后修改按钮的文本以反射(reflect)您再次单击它时的反向操作。基本上“保存到计划”变成“从计划中删除”,您可以再次单击它以执行相反的操作。
这实际上工作正常,但前提是我将要执行的 jQuery 放入 show.js.erb(以与显示按钮所在页面的方法关联的 View 命名)而不是 toggle.js.erb (基于被调用的实际方法的名称)。
在这个例子中,我使用的是 jquery-rails。
从呈现按钮的 View (show.html.erb
(更具体地说,从那里调用的部分):
<% if current_user.shows.include?(@show) %>
<p><%= button_to "Remove from schedule", toggle_show_path(@show), :remote => true, :class => 'schedule_button' %>
<% else %>
<p><%= button_to "Save to schedule", toggle_show_path(@show), :remote=> true, :class => 'schedule_button' %>
<% end %>
来自routes.rb
:
match '/shows/toggle/:id' => 'shows#toggle', :as => :toggle_show
来 self 的 `shows_controller.rb:
def toggle
if current_user
show = Show.find(params[:id])
if show
if current_user.shows.include?(show)
current_user.shows.delete(show)
flash[:notice] = "This show has been removed from your schedule."
else
current_user.shows << show
flash[:notice] = "This show has been added to your schedule."
end
else
flash[:error] = "Unknown show."
end
else
flash[:error] = "You're not logged in."
end
end
我想这里有一些默认约定决定使用哪个 .js.erb 文件,但为什么不使用基于表单提交方法的文件呢?
我一直在尝试明确告诉它要做什么,但我不太确定如何指定要调用的备用 .js.erb 文件的名称。这似乎不是它:
respond_to do |format|
format.html { redirect_to show_path(params[:id]) }
format.js { render toggle_show_path(params[:id]) }
end
来 self 的日志:
ActionView::MissingTemplate (Missing template /shows/toggle/22 with {:handlers=>[:erb, :rjs, :builder, :rhtml, :rxml], :formats=>[:js, :html], :locale=>[:en, :en]} in view paths "/Data/Sites/tvgridthing.local/app/views", "/Users/jschuur/.rvm/gems/ruby-1.9.2-p0/gems/devise-1.1.3/app/views", "/Data/Sites/tvgridthing.local", "/"):
app/controllers/shows_controller.rb:78:in `block (2 levels) in toggle'
app/controllers/shows_controller.rb:76:in `toggle'
我假设因为我想覆盖默认行为,所以我不能再使用 Rails 3 的较短的“respond_with 格式”?
不相关的问题:有什么方法可以压缩我将节目添加/删除到我的用户模型的逻辑?我正在查找、包含和添加/删除,想知道是否有更简单的解决方案。
更新:我刚刚在其他人的帮助下解决了这个问题,我将这个链接发送给了其他人。解决方案很简单:render :toggle
。
仍然好奇是否有任何关于优化切换逻辑的建议。
最佳答案
如果你改变
format.js { render toggle_show_path(params[:id]) }
只是
format.js
默认情况下,它将转到文件夹 views/shows 中名为 toggle.js.erb
的文件,因为您在 Controller 的方法切换中。
如果您在方法显示内,那么是的,您唯一的解决方案是
render :toggle
或者
render :action => 'toggle'
希望对你有帮助
关于javascript - 覆盖 Rails 远程表单提交中使用的 JavaScript 模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3895889/