rails中的简单表单无法发布数据

时间:2013-05-25 14:35:53

标签: ruby-on-rails post

我在rails中使用简单的表单。提交数据后。页面总是返回到application_form #new,数据无法保存在db中。为什么?

登录

Started POST "/application_forms" for 127.0.0.1 at 2013-05-25 19:23:28 +0800
Processing by ApplicationFormsController#create as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"yypWFcsXbdSVtp3WXUZKvstzHWsV0OOpLoGSxO1ldJ0=", "application_form"=>{"student_name"=>"somebody", ...... ,"application_type"=>"b"}, "commit"=>"Submit"}
  [1m[35mUser Load (0.0ms)[0m  SELECT "users".* FROM "users" WHERE "users"."id" = 1 LIMIT 1
  [1m[36m (0.0ms)[0m  [1mbegin transaction[0m
  [1m[35m (0.0ms)[0m  rollback transaction
  Rendered application_forms/_form.html.erb (24.0ms)
  Rendered application_forms/new.html.erb within layouts/application (25.0ms)
Completed 200 OK in 61ms (Views: 52.0ms | ActiveRecord: 0.0ms)

视图

<%= simple_form_for @application_form, :html => {:class => 'form-horizontal' } do |f| %>

  <legend>Basic Info</legend>
  <%= f.input :student_name %>
  <%= f.button :submit, 'Submit', :class => 'btn-large btn-primary'%>

<% end %>

控制器

 def create

    @application_form = ApplicationForm.new(params[:application_form])

    respond_to do |format|
      if @application_form.save
        format.html { redirect_to @application_form, :notice => 'Submit ok.' }
      else
        format.html { render :action => "new" }
      end
    end
  end

1 个答案:

答案 0 :(得分:1)

嗯,显然@application_form.save失败了。如果我不得不猜测,我猜你的模型验证失败了。当我写好一个好的模型时,偶尔会发生这种情况,包括我想要的所有验证,但后来我才开始整理一个表格而忘记包含所有需要的字段。

检查此方法的一种方法是打开

rails console

尝试这样的事情:

@application_form = ApplicationForm.new(:student_name => "student")
@application_form.save

这将完全符合您的表单正在做的事情,并且应该告诉您在尝试保存时出现的问题。

我的猜测是你也忘了在你的布局文件中包含flash消息。通常,当save失败时,您会在闪存中看到某种错误消息。由于您似乎正在使用Twitter Bootstrap(只是从表单视图中的form-horizontal类进行猜测),假设您使用twitter-bootstrap-rails gem,您只需将<%= bootstrap_flash %>添加到您的查看或模板。