我正在使用本教程:http://ruby.railstutorial.org/chapters/a-demo-app#top 我已完全按照所有步骤操作,以便向您显示我的所有相关代码。
我让应用程序工作,为第一个用户。也就是说,我在我的应用程序中添加了三个用户,但它不适用于第三个用户。我想知道我做错了什么才能发生错误信息。这是我做的:
Loading development environment (Rails 4.0.2)
2.0.0-p353 :001 > first_user = User.first
User Load (0.1ms) SELECT "users".* FROM "users" ORDER BY "users"."id" ASC LIMIT 1
=> #<User id: 1, first: "John", last: "Palfrey", email: "jpalfrey@andover.edu", status: "Confused as to why he's on Claire's application.", created_at: "2013-12-21 18:53:17", updated_at: "2013-12-21 18:53:17">
2.0.0-p353 :002 > first_user.microposts
Micropost Load (1.2ms) SELECT "microposts".* FROM "microposts" WHERE "microposts"."user_id" = ? [["user_id", 1]]
=> #<ActiveRecord::Associations::CollectionProxy [#<Micropost id: 1, content: "This is rather odd.", user_id: 1, created_at: "2013-12-21 18:56:58", updated_at: "2013-12-21 18:56:58">, #<Micropost id: 3, content: "I hope Claire can figure this out, for the sake of ...", user_id: 1, created_at: "2013-12-21 18:57:32", updated_at: "2013-12-21 18:57:32">]>
2.0.0-p353 :003 > third_user = User.third
NoMethodError: undefined method `third' for #<Class:0x007fac91453928>
from /Users/Brawain/.rvm/gems/ruby-2.0.0-p353/gems/activerecord-4.0.2/lib/active_record/dynamic_matchers.rb:22:in `method_missing'
from (irb):3
from /Users/Brawain/.rvm/gems/ruby-2.0.0-p353/gems/railties-4.0.2/lib/rails/commands/console.rb:90:in `start'
from /Users/Brawain/.rvm/gems/ruby-2.0.0-p353/gems/railties-4.0.2/lib/rails/commands/console.rb:9:in `start'
from /Users/Brawain/.rvm/gems/ruby-2.0.0-p353/gems/railties-4.0.2/lib/rails/commands.rb:62:in `<top (required)>'
from bin/rails:4:in `require'
from bin/rails:4:in `<main>'
有关为何发生这种情况的任何想法?如果你想查看我的宝石文件,我的模型等,只需查看我上面提供的链接!
提前致谢, 〜珍妮
答案 0 :(得分:4)
没有.third
这样的方法,只有.first
和.last
。您需要尝试User.find(3)
,它会按用户ID查找用户。
你会发现这很有用 - http://guides.rubyonrails.org/active_record_querying.html
答案 1 :(得分:1)
没有User.third
这样的方法,您可以使用:User.find(3)
其中3是第三个用户的ID。
如果您不确定第三个用户的ID是否为3,那么您可以执行以下操作:
User.take(3).last