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

artone · 2012年08月27日 · 最后由 chinacheng 回复于 2012年08月31日 · 3039 次阅读

小弟初学 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 就不行,不知何故?

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

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

  redirect_to :action => :index
end

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

匿名 #3 2012年08月27日

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

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

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

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