As discussed in http://edgeguides.rubyonrails.org/4_0_release_notes.html#general, Model.all
now returns an ActiveRecord::Relation
rather than an Array
. While a Relation
supports many of the methods that an Array
does (e.g. each
), it does not support empty?
. The to_a
converts it to an Array
so that the empty tests can function.
dup method not working after migrating Rails 3.2 → 4.0
-
03-06-2022 - |
题
After following the Rails 4.0 supplement, I got to the Some specific issues part, where Michael mentions
One tiny change in the Micropost spec (
spec/models/micropost_spec.rb
) is a change from thedup
method (to duplicate the user’s user-microposts) to theto_a
method (which converts them to an array). Here is the version withdup
:
Rails 3.2
it "should destroy associated microposts" do
microposts = @user.microposts.dup
@user.destroy
microposts.should_not be_empty
microposts.each do |micropost|
Micropost.find_by_id(micropost.id).should be_nil
end
end
Rails 4.0
it "should destroy associated microposts" do
microposts = @user.microposts.to_a
@user.destroy
expect(microposts).not_to be_empty
microposts.each do |micropost|
expect(Micropost.where(id: micropost.id)).to be_empty
end
end
He himself says he doesn't fully understand the need to change the method:
For reasons obscure to me, the call to
dup
no longer works in Rails 4.0, but replacing it withto_a
works fine.
So why doesn't dup
work anymore?
解决方案
不隶属于 StackOverflow