a == b returns 真,a.attribute == b.attribute returns 假; ruby
a == b returns true, a.attribute == b.attribute returns false; ruby
我正在测试控制器的这一行:
@channel.update_attribute(:active, true)
expect(channel.active).to be_true fails (my variable is named 'channel')
expect(assigns[:channel].active).to be_true passes
assigns[:channel] == channel
=> true
assigns[:channel].active == channel.active
=> false
assigns[:channel].active == channel.reload.active
=> true
我不明白为什么比较运算符说assigns[:channel] == channel,但是他们的"active"属性不同。
我假设一个通道是一个 ActiveRecord 对象,它和做的是一样的:
channel1 = Channel.find(1)
channel2 = Channel.find(1)
所以channel1 == channel2
因为他们的身份是一样的。 (他们都是频道并且有相同的id)
但是如果你更新其中一个,另一个就会过时。
channel1.active = "different value"
channel1.save
channel1.active != channel2.active
channel2.reload
将从数据库中获取属性,现在
channel1.active == channel2.active
http://api.rubyonrails.org/classes/ActiveRecord/Core.html#method-i-3D-3D
因为 ActiveRecord 模型的相等性基于它们的 ID,而不是每个属性。所以它是同一个模型,它们只是 "active" 属性的设置不同。这就是它在您重新加载后起作用的原因。
我认为如果您更改第一行,它可能会像您预期的那样工作:
@channel.update(active: true)
我不确定究竟在你的具体情况下发生了什么,但一般情况一点也不奇怪:
class Foo
attr_reader :bar
def initialize
@bar = Bar.new
end
def ==(*) true end
class Bar
def ==(*) false end
end
end
a = Foo.new
b = Foo.new
a == b
# => true
a.bar == b.bar
# => false
这只是面向对象封装的结果。是否认为等于b
由a
决定,是否认为等于[=14]由a.bar
决定=],并且没有强制要求两者必须同意。
在您的情况下,似乎存在一些缓存一致性问题。您似乎有两个不同的对象,它们都代表相同的数据库记录,并且其中一个具有陈旧数据。
我正在测试控制器的这一行:
@channel.update_attribute(:active, true)
expect(channel.active).to be_true fails (my variable is named 'channel')
expect(assigns[:channel].active).to be_true passes
assigns[:channel] == channel
=> true
assigns[:channel].active == channel.active
=> false
assigns[:channel].active == channel.reload.active
=> true
我不明白为什么比较运算符说assigns[:channel] == channel,但是他们的"active"属性不同。
我假设一个通道是一个 ActiveRecord 对象,它和做的是一样的:
channel1 = Channel.find(1)
channel2 = Channel.find(1)
所以channel1 == channel2
因为他们的身份是一样的。 (他们都是频道并且有相同的id)
但是如果你更新其中一个,另一个就会过时。
channel1.active = "different value"
channel1.save
channel1.active != channel2.active
channel2.reload
将从数据库中获取属性,现在
channel1.active == channel2.active
http://api.rubyonrails.org/classes/ActiveRecord/Core.html#method-i-3D-3D
因为 ActiveRecord 模型的相等性基于它们的 ID,而不是每个属性。所以它是同一个模型,它们只是 "active" 属性的设置不同。这就是它在您重新加载后起作用的原因。
我认为如果您更改第一行,它可能会像您预期的那样工作:
@channel.update(active: true)
我不确定究竟在你的具体情况下发生了什么,但一般情况一点也不奇怪:
class Foo
attr_reader :bar
def initialize
@bar = Bar.new
end
def ==(*) true end
class Bar
def ==(*) false end
end
end
a = Foo.new
b = Foo.new
a == b
# => true
a.bar == b.bar
# => false
这只是面向对象封装的结果。是否认为等于b
由a
决定,是否认为等于[=14]由a.bar
决定=],并且没有强制要求两者必须同意。
在您的情况下,似乎存在一些缓存一致性问题。您似乎有两个不同的对象,它们都代表相同的数据库记录,并且其中一个具有陈旧数据。