我(我认为是)一个非常标准的对象要保存在Rails 4中:
create_table "games", force: true do |t|
t.string "sport", default: "", null: false
t.string "opponent", default: "", null: false
t.datetime "date"
t.integer "home_score", default: 0, null: false
t.integer "op_score", default: 0, null: false
t.boolean "active", default: true, null: false
t.boolean "final", default: false, null: false
t.datetime "created_at"
t.datetime "updated_at"
end
对象本身:
sport: "Foosball", opponent: "New York",
date: "2013-12-31 00:00:00",
home_score: 100, op_score: 0, active: false, final: true,
game.rb
:
class Game < ActiveRecord::Base
validates_presence_of :opponent, :sport
before_save :check_active
scope :active, -> { where(active:true) }
def check_active
if self.date <= (Date.today - 4)
self.active = false;
end
end
end
但是,当我去保存对象时:
pry(#<GamesController>)> @game.save
(0.1ms) begin transaction
(0.1ms) rollback transaction
=> false
[14] pry(#<GamesController>)> @game.errors.messages
=> {}
发生了什么事?我注意到服务器也返回422 unproccessable entity
,但我不确定这是怎么回事。该对象在各方面都很好。
答案 0 :(得分:1)
我认为你的check_active返回false,这会阻止保存。您显然可以返回true:
def check_active
if self.date <= (Date.today - 4)
self.active = false;
end
true
end
取消回调
如果before_ *回调返回false,则取消所有后续回调和相关操作。回调通常按照定义的顺序运行,但定义为模型上的方法的回调除外,这些回调最后被调用。