新手问题 进入每个页面为什么会执行两次方法

tianlitao · 2014年11月17日 · 最后由 michael_roshen 回复于 2014年11月18日 · 3306 次阅读

比如我要进入 index 页面会执行两次

def index
end

方法,不知道为什么,求大牛解惑

show me the log

可能是 /favicon.ico 导致的

talk is cheap, show me the code.

#3 楼 @xiaoronglv

for i in @messages
    if i.status_one=="1"
      i.status="1"
      else
      i.status_one="1"
    end
  i.save
end

我这里想要实现的效果是站内信的功能,@messages为从数据库取出符合的信息,第一次接收到信息并进去 messages 页面,信息标志为 new,再次刷新页面,信息标志为已读,status_one 默认为空,不知道为何会执行两次,直接就置为已读状态,后来我又添加了一个属性,功能是可以实现了

    for i in @messages
 if i.sender=="1"
        if i.status_one=="1"
          i.status="1"
          else
          i.status_one="1"
        end
      i.save
else
i.sender="1"
    end

代码写的不好看,见谅

之前我做过一个项目也是站内消息,也发生过执行 2 次方法将消息的状态变为已读,后面发现是 rails 自带的 turbolinks 有问题,然后升级 turbolinks 的版本后问题就没有出现过了

#6 楼 @kai209209 我试了,如果注释掉

 gem 'turbolinks'
//= require turbolinks

方法只执行一次,可以实现,turbolinks 应该是最新的,不知道具体原因. 看了@Rei 的这篇文章 http://chloerei.com/2013/07/14/turbolinks-guide/ 不知道@Rei 清楚么

#7 楼 @tianlitao 没看懂代码,什么 action 被访问了两次,路由是什么,页面代码是怎么写的,是 ajax 还是 html,什么操作可以重现问题?

#8 楼 @Rei 点击 link

<p><%= link_to "站内信",check_messages_path,:style => "color:red" %>

routes

get 'check_messages'=>'users#check_messages'

这个会执行两次,如果只是刷新 check_messages 页面的话是只执行一次

def check_messages
  @messages=Message.where(:receive => current_user.id.to_s).order(id: :desc)
  for i in @messages

      if i.status_one=="1"
        i.status="1"
      else
        i.status_one="1"
    end
    i.save
  end
end

是不是有什么 assets 添加了 data-turbolinks-track 属性,然后两个页面拥有的 assets 不同的?

检查下页面里面有没有类似 这样的标签

#12 楼 @tianlitao 我记得之前我遇到过 有这样的标签或者都会调用一次当前页面

Events firing twice or more

If you find that some events are being fired multiple times after using jQuery Turbolinks, you may have been binding your document events inside a $(function()) block. For instance, this example below can be a common occurrence and should be avoided:

/* BAD: don't bind 'document' events while inside $()! */ $(function() { $(document).on('click', 'button', function() { ... }) });

You should be binding your events outside a $(function()) block. This will ensure that your events will only ever be bound once.

/* Good: events are bound outside a $() wrapper. */ $(document).on('click', 'button', function() { ... })

需要 登录 后方可回复, 如果你还没有账号请 注册新账号