新手问题 form_for 传回资料无法写入数据库

artone · 发布于 2012年8月27日 · 最后由 chinacheng 回复于 2012年8月31日 · 1499 次阅读
3417

小弟初学 Rails 照著书走,碰到个问题,求各位解惑。原本预期透过 new 页面建立 event,已经给了所有参数,但是值无法存入资料库,看了 rails s 的 log 有这么条记录:

Started POST "/events/create" for 127.0.0.1 at 2012-08-27 10:34:10 +0800
Processing by EventsController#create as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"zN+LjiYDfXHL40xG6Wqo8gVhH1Z9+dYkgEc3yHKZChw=", "event"=>{"name"=>"123", "description"=>"123"}, "commit"=>"Create"}
   (0.1ms)  begin transaction
  SQL (4.0ms)  INSERT INTO "events" ("capacity", "created_at", "description", "is_public", "name", "updated_at") VALUES (?, ?, ?, ?, ?, ?)  [["capacity", nil], ["created_at", Mon, 27 Aug 2012 02:34:10 UTC +00:00], ["description", nil], ["is_public", nil], ["name", nil], ["updated_at", Mon, 27 Aug 2012 02:34:10 UTC +00:00]]
   (1.4ms)  commit transaction
Redirected to http://127.0.0.1:3000/events
Completed 302 Found in 9ms (ActiveRecord: 5.5ms)

明明已经给了 name、description 的值为 123,写入资料库时却是 nil?


我的代码如下:events controller

class EventsController < ApplicationController
  def index
    @events = Event.all
  end

  def new
    @event = Event.new
  end

  def create
    @event = Event.new(params[:id])
    @event.save

    redirect_to :action => :index
  end
end

index.html.erb

<ul>
  <% @events.each do |event| %>
  <li>
    <%= event.name %>
  </li>
  <% end %>
</ul>

<%= link_to 'New event', :controller => 'events', :action => 'new' %>

new.html.erb

<%= form_for @event, :url => { :controller => "events", :action => "create" } do |f| %>
  <%= f.label :name, "Name" %>
  <%= f.text_field :name %>

  <%= f.label :description, "Description" %>
  <%= f.text_area :description %>

  <%= f.submit "Create" %>
<% end %>

PS. 透过 rails cevent = Event.new( :name => "blahblah" ) 就可以,透过 form_for 就不行,不知何故?

共收到 5 条回复
3417

自己解答……原来是 create 方法写错了……orz

def create
  @event = Event.new(params[:event])
  @event.save

  redirect_to :action => :index
end
1189

虚惊一场 ,代码打错字是常事。

1267

呵呵,一眼就瞄到你错哪了

96

"utf8"=>"✓", "authenticity_token"=>"zN+LjiYDfXHL40xG6Wqo8gVhH1Z9+dYkgEc3yHKZChw=" 这2个默认参数是用来做什么的呢?

947

#4楼 @firsthym 第二个是rails用来做表单验证机制的,防Cross Site Request Forgery

需要 登录 后方可回复, 如果你还没有账号请点击这里 注册