Rails link_to with remote: true 在页面刷新后处理 html 而不是 js [英] Rails link_to with remote: true processing html instead of js after page refresh

查看:45
本文介绍了Rails link_to with remote: true 在页面刷新后处理 html 而不是 js的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用中有一个搜索页面,其中有一个 ajax 搜索表单.搜索表单正常工作,将参数传递给模型以过滤搜索,并且模型返回结果集合.搜索提交后,@results 会呈现在页面上.然后每个@result 都有一个指向它的操作的链接,例如:

I have a search page in my app, where there is an ajax search form. The search form works properly, passing parameters to the model to filter the search, and the model returning a collection of results. Upon search submit, @results are rendered on the page. Each @result then has a link to an action on it, like:

<%=link_to "Message", message_user_path(:id => user.id), :remote => true%>

控制器中的这个动作在哪里:

Where this action in the controller is:

respond_to :js, :html
def message
  @user_id = params[:id]
  @user = User.find_by_id(@user_id)
  respond_to do |format|
    format.html
    format.js
  end
end

这会以 message.js.erb 进行响应,这会触发消息面板向用户弹出一条消息.所有这些都正常工作,检查日志我看到发送了正确的 get 请求,并且正在处理正确的格式:

and this responds with message.js.erb, which triggers a messaging panel to pop up with a message to the user. All of this is working correctly, checking the log I see the correct get request sent, and the correct format being processed:

Started GET "/users/3/message"
Processing by UsersController#message as JS

但是,如果我刷新页面并尝试单击之前可用的相同链接,我会收到错误模板缺失.查看日志,我看到现在发送了两个请求,第一个是 html,然后是同一个 js 请求.

However, if I refresh the page and try to click the same link that was working before, I get the error Template is Missing. Checking the log, I see that now there are two requests sent, first an html then the same js request.

Started GET "/users/4/message"
Processing by StudentsController#message as HTML
...
Completed 406 Not Acceptable in 3ms (ActiveRecord: 1.0ms)

Started GET "/users/4/message"
Processing by StudentsController#message as JS

html 请求抛出缺少模板错误.有谁知道为什么刷新页面会导致 rails 尝试使用对远程链接的 html 请求进行响应?
routes.rb

The html request throws the missing template error. Does anyone know why refreshing the page causes rails to attempt to respond with an html request to a remote link?
routes.rb

resources :students do
    member do
      get 'message'
    end
end

推荐答案

你的 app/assets/javascripts/application.js 是否包含

//= require jquery
//= require jquery_ujs 

?

并且您的 erb 包含 <%= javascript_include_tag "application" %>?

And your erb contains <%= javascript_include_tag "application" %>?

我只是在 HOURS 上为这样的问题苦苦挣扎,这两点中的最后一点修复了它;我在其他一些问题中看到了第一点,所以我在这里重复一遍.

I was just struggling with a problem like this for HOURS and the last of those two points fixed it; I saw the first point mentioned in some other questions so I'll repeat it here.

希望有所帮助.

(信用到期的信用)

这篇关于Rails link_to with remote: true 在页面刷新后处理 html 而不是 js的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆