Rails 在页面表单里,填完数据后提交,无法保存到数据表是什么原因?

gsky · 2015年03月24日 · 最后由 justin 回复于 2015年03月24日 · 2365 次阅读

我在一个页面表单里填完了数据,点击提交后,一直无法跳转到成功页面,查了下数据库,数据没有保存进来,看日志也没看出原因...求助

控制器里 create 动作的代码:

def create
     @factor = current_user.factors.build(factor_params)
     @result = Result.new
     if @factor.save
        @result.factor_id = @factor.id
       calculate_result(@factor,@result)
       flash[:success] = "TPI因子录入成功"
       redirect_to @result

     else
       render 'new'
     end
end

日志:

Started POST "/factors" for ::1 at 2015-03-24 11:00:19 +0800
Processing by FactorsController#create as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"Sf6rMqgnQoQtcc2LcII4qOaPmh0k8aXLYl5OzDzCSj2WK5Oq6mKZtGwaCpMIjPXjDtILwYO5uRZoJeqaRX5j+g==", "factor"=>{"name"=>"39", "a"=>"9", "b"=>"9", "c"=>"9", "d"=>"9", "e"=>"9", "f"=>"9", "g"=>"9", "h"=>"9", "i"=>"9", "j"=>"9", "k"=>"9", "l"=>"9", "m"=>"9", "n"=>"9", "o"=>"9", "s"=>"", "p"=>"9", "q"=>"9", "r"=>"9", "aa"=>"9", "bb"=>"9", "cc"=>"9", "dd"=>"99", "ee"=>"", "ff"=>"99", "gg"=>"9", "hh"=>"9", "ii"=>"9", "jj"=>"9", "kk"=>"9", "ll"=>"9", "aaa"=>"9", "ccc"=>"9", "ddd"=>"99", "eee"=>"9", "fff"=>"9"}, "commit"=>"确认生成TPI统计结果"}
  User Load (0.1ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1  [["id", 1]]
   (0.1ms)  begin transaction
   (0.1ms)  rollback transaction
  Rendered layouts/_factor.html.erb (13.1ms)
  Rendered factors/new.html.erb within layouts/application (14.2ms)
  Rendered layouts/_shim.html.erb (0.1ms)
  Rendered layouts/_header.html.erb (1.8ms)
Completed 200 OK in 416ms (Views: 240.0ms | ActiveRecord: 1.7ms)

找到原因了, 因为在 model 给这些表单里的字段全部加上了类似于这种validates :a,presence:true校验. 可是为什么加上存在性校验后,提交了无法在数据表保存呢?

建议 debugger,然后用@factor.save! 看一下哪里报错了。

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