Ruby on Rails - 调用html.erb和js.erb
Ruby on Rails - 调用html.erb和js.erb
我的目标是在同一个控制器中调用一个html.erb文件和一个js.erb文件,但是它只调用了我的html文件。
我的js没有被调用。\n
controller/categories_controller.rb\n
def index respond_to do |format| format.html format.js end @categories = Category.order('name ASC') @category = params[:category] end
\nview/categories/index.html.erb\n
<% @categories.each do |c| %> <%= link_to c.name, show_category_path(category: c.id), :id => "btn-filter#{c.id}" %> <% end %>
\nviews/categories/index.js.erb(问题出在这里,这个文件没有被调用)\n
alert("test"); $("#btn-filter<%=@category%>").attr("class","active");
在Ruby on Rails中,有时候我们需要同时调用html.erb和js.erb文件。下面是一个示例代码:
<% @categories.each do |c| %> <%= link_to c.name, show_category_path(category: c.id), remote: true, :id => "btn-filter#{c.id}" %> <% end %>
这段代码中,我们使用了`link_to`方法来生成一个链接,该链接会调用`show_category_path`这个路径,并传递一个名为`category`的参数。我们通过`remote: true`选项告诉Rails这是一个远程请求,同时也会自动寻找名为`index.js.erb`的文件。
这个问题的出现原因是,我们希望同时调用html.erb和js.erb文件来实现一些动态交互的效果。而在Rails中,默认情况下,如果我们没有指定`remote: true`选项,那么Rails会认为这是一个普通的同步请求,只会调用html.erb文件。但是当我们添加了`remote: true`选项后,Rails会自动寻找对应的js.erb文件。
解决这个问题的方法就是在`link_to`方法中添加`remote: true`选项。这样Rails就会同时调用html.erb和js.erb文件,实现我们所需的动态交互效果。
希望本文能对你理解Ruby on Rails中同时调用html.erb和js.erb文件的问题有所帮助。如果你还有其他问题,欢迎随时提问。
问题的原因是,控制器根据请求所要求的格式进行响应,因此,链接请求的是HTML格式,而不是JS格式,因此控制器会响应.html.erb
文件。如果添加以下调用:
<%= link_to c.name, show_category_path(category: c.id), :id => "btn-filter#{c.id}", remote: true %>
由于remote: true
属性,请求将要求JS格式,而控制器将响应.js.erb
文件。
解决方法是,在控制器中添加条件,以根据请求的格式来选择性地呈现HTML或JS视图。可以使用respond_to
和respond_with
方法来实现这一目的。下面是一个示例代码:
def show_category @category = Category.find(params[:category]) respond_to do |format| format.html format.js end end
在上面的代码中,respond_to
块将根据请求的格式来选择性地呈现HTML或JS视图。在控制器中定义的HTML视图将被呈现为.html.erb
文件,而JS视图将被呈现为.js.erb
文件。
这样,当链接请求时,如果设置了remote: true
属性,控制器将根据请求的格式选择性地呈现HTML或JS视图,从而解决了问题。