Simple form in rails can't post data

孤街浪徒 提交于 2020-01-06 14:21:25

问题


I use simple form in rails. After submit data. the page always return to application_form#new, and data can't be saved in db. Why?

log

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)

View

<%= 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 %>

Controller

 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:


Well, clearly @application_form.save is failing. If I had to guess, I'd guess you've got a validation on your model that's failing. This happens to me occasionally when I've written a good model, including all the validations I will want, but then I'm just starting to put together a form and I forget to include all the fields that need to be there.

One way to check this is to open up

rails console

and try something like this:

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

This will do pretty much exactly what your form is doing, and should tell you what the problem is when you try to save.

My guess is that you've also forgotten to include flash messages in your layout file. Usually you'll see some sort of error message in your flash when save fails. Since it seems like you're using Twitter Bootstrap (just guessing from the form-horizontal class on your form view), assuming your using the twitter-bootstrap-rails gem, you can just add <%= bootstrap_flash %> to either your view or your template.



来源:https://stackoverflow.com/questions/16750558/simple-form-in-rails-cant-post-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!