Rails:为什么我的灯具有相同的ID?

时间:2017-05-31 21:00:44

标签: ruby-on-rails

我开始写测试了:

class PostPresenterTest < ActionView::TestCase
  let(:presenter) { PostPresenter.new(post, view) }
  let(:post) { Post.first }

  it 'should something something...' do
    byebug
  end
end

我有post.yml灯具文件:

  one:
    title: Title One
    content: First content.

  two:
    title: Title Two
    content: Second content.

当我进入byebug时,我注意到Post.count == 2但个别帖子具有相同的ID:

  Post.first.id == 298486374
  Post.last.id == 298486374

这是预期的吗?我需要确保每个帖子都有自己唯一的ID。添加ID到固定装置的轨道标准是什么?我应该手动添加ID还是应该采取特定步骤来确保帖子具有不同的ID?

1 个答案:

答案 0 :(得分:1)

问题在于我假设Post.firstPost.last返回了不同的帖子。他们实际上回复了同一个帖子。 ids 不同。

(byebug) Post.all
#<ActiveRecord::Relation [#<Post id: 298486374, title: "Title Two", content: "Second content.", created_at: "2017-06-01 06:44:50", updated_at: "2017-06-01 06:44:50">, #<Post id: 980190962, title: "Title One", content: "First content.", created_at: "2017-06-01 06:44:50", updated_at: "2017-06-01 06:44:50">]>

我尝试了Post.order("created_at").firstPost.order("created_at").first,但那些也回复了相同的帖子。我意识到这是因为这两个帖子都有相同的创建日期。手动添加日期可修复此问题。 #last#first现在返回不同的帖子。