我是一名新的 Rails 开发人员,试图获取以下网址:
www.twitter.com/theusername
这是我的路线:
match "/:username" => "posts#index"
这工作并将我的 localhost:3000/theusername 路由到 localhost:3000/posts/
然后我使用:
def index
@user = User.find_by_username params[:username]
@search = Post.search do
fulltext params[:search]
with(:user, @user.id)
paginate(:page => params[:page] || 1, :per_page => 20)
end
end
不幸的是,这带来了错误:
为 nil 调用 id,它会错误地为 8——如果你真的想要 nil 的 id,使用 object_id
此外,Web 服务器会显示此内容(以防万一):
Processing by PostsController#index as HTML
Parameters: {"username"=>"test"}
User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."id" = 2 LIMIT 1
User Load (0.1ms) SELECT "users".* FROM "users" WHERE "users"."username" = 'test' LIMIT 1
Completed 500 Internal Server Error in 2ms
RuntimeError (Called id for nil, which would mistakenly be 8 -- if you really wanted the id of nil, use object_id):
app/controllers/posts_controller.rb:10:in `block in index'
app/controllers/posts_controller.rb:8:in `index'