Вопрос

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 the dup method (to duplicate the user’s user-microposts) to the to_a method (which converts them to an array). Here is the version with dup:

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 with to_a works fine.

So why doesn't dup work anymore?

Это было полезно?

Решение

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.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top