新手问题 不同的方式获取 AR 记录,AR 记录中的 Boolean 值产生差异

aijinsong · 2015年05月07日 · 最后由 aijinsong 回复于 2015年05月27日 · 1753 次阅读

通过 all 获取的数据 ID 为 5 的 active 为 false 是对的。但是通过 current_account.room 获取的数据 ID 为 5 的 active 为 true 是错的。 为何会因为获取的方式不一致,导致数据问题?

@rooms = current_account.rooms
@rooms.each { |room| puts "#{room.id}:#{room.active?}" }

打印的日志为:

DEBUG -  Room Load (0.4ms)  SELECT `rooms`.* FROM `rooms` WHERE `rooms`.`account_id` = 8
4:true
5:true
@rooms = Room.all
@rooms.each { |room| puts "#{room.id}:#{room.active?}" }

打印的日志为:

DEBUG -  Room Load (0.2ms)  SELECT `rooms`.* FROM `rooms` 
1:true
2:true
3:true
4:true
5:false

枚举发出来看看

#1 楼 @cysh 5 条 active 的值为:1 1 1 1 0。active 字段为 tinyint 类型。

rooms 的 primary key 是什么?

#3 楼 @ditsing room 的 id。是通过 AR 管理的。

Room.find(5).active? 是什么

这要是个 bug 那也太奇葩了。

可能是 current_account.rooms 已经缓存过一次了,然后 某个地方 修改了 rooms.find(5) 这个 model 的值

这个时候 你可以 current_account.rooms.reload 重新从数据库读取一次 就 ok 了

#6 楼 @meeasyhappy 这个可能不能作为正式环境的方案。另,我的代码流程很简单,不会有你说的这类操作的。

#5 楼 @ditsing 非常感谢您的回复,测试稍晚,望谅解。

DEBUG -  Room Load (0.3ms)  SELECT `rooms`.* FROM `rooms` WHERE `rooms`.`id` = 5 LIMIT 1
false

另,今天使用 current_account.rooms 测试发现又没有问题了。特别费解。

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