导轨 3.2.8
我试图创建一个简单的多态 Log 模型作为可记录的。该表只有一个字段 log,它被设想为只是一个时间戳,并且一条短消息将附加到 has_one 关系。
我的问题是创建记录后,我似乎无法获取要附加和保存的消息。调试显示它已提交并且记录已更改,但当它重新加载时,它会恢复到原始版本。我一直在研究这种方式很长时间,现在是时候看看其他人是否看到了一些愚蠢的东西。
模型的相关部分:
class Log < ActiveRecord::Base
belongs_to :logable, :polymorphic => true
attr_accessible :logable_id, :log, :logable_type
def set_log(entry)
self.log << "\r\n#{Time.now.to_s} - #{entry}"
self.save
end
end
class Candidate < ActiveRecord::Base
attr_accessible :citizen_id, :commitment_id, :current_stage, :current_status
has_one :log, :as => :logable
def append_log(entry)
if self.log.nil?
self.build_log( :log => "#{Time.now.to_s} - Log Created")
self.log.save
end
self.log.set_log(entry)
end
end
下面是我获得候选人的控制台日志,查看日志(仅限原始创建的条目),附加一个条目,显示在实例中所做的更改。重新加载日志记录,更改就消失了。
1.9.2-p136 :001 > c = Candidate.find(1)
Candidate Load (15.1ms) SELECT "candidates".* FROM "candidates" WHERE "candidates"."id" = ? LIMIT 1 [["id", 1]]
1.9.2-p136 :002 > c.log
Log Load (0.1ms) SELECT "logs".* FROM "logs" WHERE "logs"."logable_id" = 1 AND "logs"."logable_type" = 'Candidate' LIMIT 1
=> #<Log id: 1, logable_id: 1, logable_type: "Candidate", log: "2012-11-16 15:23:49 -0600 - Log Created", created_at: "2012-11-16 21:23:49", updated_at: "2012-11-16 21:23:49">
1.9.2-p136 :003 > c.append_log("Add entry")
LOG BEFORE 2012-11-16 15:23:49 -0600 - Log Created
(0.1ms) begin transaction
(0.1ms) commit transaction
LOG APPENDED 2012-11-16 15:23:49 -0600 - Log Created
2012-11-16 16:05:53 -0600 - Add entry
NOTE Log field has been appended
=> nil
1.9.2-p136 :004 > c.log
=> #<Log id: 1, logable_id: 1, logable_type: "Candidate", log: "2012-11-16 15:23:49 -0600 - Log Created\r\n2012-11-16...", created_at: "2012-11-16 21:23:49", updated_at: "2012-11-16 21:23:49">
NOTE Now reload the log record
1.9.2-p136 :005 > l = Log.find(1)
Log Load (0.3ms) SELECT "logs".* FROM "logs" WHERE "logs"."id" = ? LIMIT 1 [["id", 1]]
=> #<Log id: 1, logable_id: 1, logable_type: "Candidate", log: "2012-11-16 15:23:49 -0600 - Log Created", created_at: "2012-11-16 21:23:49", updated_at: "2012-11-16 21:23:49">
NOTE The add entry line is gone!
我不知道这是否是 has_one 关系的问题,但即使我只使用日志记录调用 set_log,at 似乎也会附加,但重新加载没有更改。
难倒史蒂夫