我想在rails应用程序中使用angularjs
。为此,我将数据从angularjs发布到rails服务器然后我想如果服务器不将数据保存到数据库,我将错误从rails服务器发送到angularjs部分。我使用下面的代码来完成这项工作:
bolouks_controller.rb
:
def create
@bolouk = Bolouk.create(bolouk_params)
if @bolouk.save #always true
respond_with @bolouk, :location => api_bolouks_path
else
respond_with @bolouk.errors, :location => api_bolouks_path
end
end
model/bolouk.rb
:
class Bolouk < ActiveRecord::Base
validates_length_of :south, :minimum => 5, :presence => true
end
但是当我将数据发布到rails服务器时,如果数据无效,数据不会保存到数据库,但我在服务器日志中得到 Completed 201 Created in 32ms (Views: 1.0ms | ActiveRecord: 2.0ms)
。我知道这个问题的原因。 if @bolouk.save
声明始终为真。
server log
:
Started POST "/api/bolouks.json" for 127.0.0.1 at 2014-09-08 10:31:40 +0430
Processing by Api::V1::BolouksController#create as JSON
Parameters: {"south"=>"", "bolouk"=>{"south"=>""}}
User Load (0.0ms) SELECT "users".* FROM "users" WHERE "users"."id" = 7 ORDER BY "users"."id" ASC LIMIT 1
(0.0ms) begin transaction
(0.0ms) rollback transaction
(0.0ms) begin transaction
(1.0ms) rollback transaction
Completed 201 Created in 37ms (Views: 0.0ms | ActiveRecord: 2.0ms)
我不知道为什么if @bolouk.save
总是如此?如何更改create
操作代码以优化代码和.save
语句正常工作?任何人都有任何想法来解决此问题?
答案 0 :(得分:1)
任何带有惊叹号的东西,如果不是,就会引发错误 成功
所以save!
代替save
来显示您的验证错误
你的方法看起来像
def create
@bolouk = Bolouk.create(bolouk_params)
if @bolouk.save!
respond_with @bolouk, :location => api_bolouks_path
else
respond_with @bolouk.errors, :location => api_bolouks_path
end
end
在错误后执行
def create
begin
@bolouk = Bolouk.create(bolouk_params)
@bolouk.save!
respond_with @bolouk, :location => api_bolouks_path
rescue ActiveRecord::RecordInvalid, ActiveRecord::RecordNotSaved
respond_with @bolouk.errors, :location => api_bolouks_path
end
end
答案 1 :(得分:0)
我想问题出在验证上,请试试这个
validates :south, :length => {:minimum => 5}, :presence => true
或将每个验证分开:
validates_presence_of :south
validates_length_of :south, minimum: 5