以下是代码段及其结果输出。代码似乎更新了属性,但是当我在数据库中手动检查记录时,没有任何更改。这是由.changed确认的吗?返回假。我做错了什么?
class Ticket < ActiveRecord::Base
##+-----------------+-----------------------+------+-----+---------+-------+
##| Field | Type | Null | Key | Default | Extra |
##+-----------------+-----------------------+------+-----+---------+-------+
##| ticketid | bigint(20) unsigned | NO | PRI | NULL | |
##| ticketnumber | bigint(20) unsigned | NO | | NULL | |
##| contactname | char(40) | YES | | NULL | |
##| department | char(40) | YES | | NULL | |
##| tech | char(40) | YES | | NULL | |
##| timeopened | char(18) | YES | | NULL | |
##| timelastchanged | char(18) | YES | | NULL | |
##| mintuesopen | mediumint(8) unsigned | YES | | NULL | |
##| searchtermlist | varchar(255) | YES | | NULL | |
##+-----------------+-----------------------+------+-----+---------+-------+
attr_accessible :searchtermlist, :minutesopen, :timelastchanged, :tech
end
....
thisticket = Ticket.find_by_ticketid(ticketid)
if thisticket != nil
puts "---Ticket #{ticketid} Found!"
if thisticket.searchtermlist.include? importedsearchtermlist
puts "---Search term list current! Skipping..."
else
puts "---Updating search term list for ticket #{ticketid}"
puts importedsearchtermlist
puts thisticket.ticketid
puts thisticket.searchtermlist
updatedsearchtermlist = thisticket.searchtermlist << "," << importedsearchtermlist
puts updatedsearchtermlist
thisticket.searchtermlist = updatedsearchtermlist
result = thisticket.save!
puts result
puts thisticket.changed?
puts thisticket.searchtermlist
sleep(60)
end
输出:
---Ticket 47048 Found!
---Updating search term list for ticket 47048
virus
47048
update
update,virus
true
false
update,virus
答案 0 :(得分:1)
使用<<
不会更改属性值。您可以使用thisticket.changes
返回哈希检查,其中不包含更改的值。所以尝试使用:
updatedsearchtermlist += ( ',' + importedsearchtermlist)
或:
updatedsearchtermlist = [updatedsearchtermlist, importedsearchtermlist].join(',')
而不是:
updatedsearchtermlist = thisticket.searchtermlist << "," << importedsearchtermlist
修复后,changed?
将返回false
(在您的调试结果中)。因为,您在保存记录后正在检查它。因此它将始终返回false
。