UGC没有被创建

时间:2011-10-15 06:48:51

标签: ruby-on-rails ruby

我正在尝试创建用户生成的帖子。我知道这些帖子是在 db,但没有显示。终点站:

User Load (0.1ms)  SELECT "users".* FROM "users" WHERE "users"."id" = 1 LIMIT 1
  SQL (18.4ms)  INSERT INTO "events" ("content", "created_at", "updated_at",
    "user_id") VALUES (?, ?, ?, ?)  [["content", "Test post."], ["created_at",
    Sat, 15 Oct 2011 06:36:49 UTC +00:00], ["updated_at",
    Sat, 15 Oct 2011 06:36:49 UTC +00:00], ["user_id", 1]]
Redirected to http://localhost:3000/events
Started GET "/events" for 127.0.0.1 at Sat Oct 15 00:36:49 -0600 2011
  Processing by EventsController#show as HTML
Completed 404 Not Found in 1ms

ActiveRecord::RecordNotFound (Couldn't find Event without an ID):
  app/controllers/events_controller.rb:22:in `show'

说同样的话,但我的应用程序给了我同样的错误:

Couldn't find Event without an ID
app/controllers/events_controller.rb:22:in `show'

这是我的Events_Controller方法“show”的问题:

def show
  @title  = "Your Events"
  @event  = Event.find(params[:id])
end

或例行问题?我正在尝试显示所有已创建事件的索引。

提前感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

line 13上的EventsController中,您有:

redirect_to events_path

我认为这对应于上面日志中的第六行(“Redirected to http://localhost:3000/events”)。

但是,当您使用redirect_to时,它会发起新的GET请求,因为您没有指定任何参数params因此为空。这就是为什么params[:id] nilEvent.find(params[:id])会引发您所看到的错误的原因。

您确定不应该使用redirect_torender :action => :show,而不是使用render :action => :index?与redirect_to不同,render不会发起新请求,它只是呈现指定的视图,但在当前上下文中(在您的情况下,@event已定义。

有关renderredirect_to的详细信息,请特别阅读Rails Guide on Layouts and Rendering第2部分。