我有一个购买模型has_one
优惠券。
购买模型包含以下代码:
def decrement_coupon
coupon = Coupon.find_by_code(coupon_code, :readonly => false)
return unless coupon.respond_to?(:uses)
coupon.uses = coupon.uses - 1
coupon.save
end
但是前几天我收到了这个错误:
ActiveRecord::ReadOnlyRecord - ActiveRecord::ReadOnlyRecord:
/usr/local/rvm/gems/ree-1.8.7-2010.02@lyconic/gems/activerecord-3.0.6/lib/active_record/persistence.rb:245:in `create_or_update'
/usr/local/rvm/gems/ree-1.8.7-2010.02@lyconic/gems/activerecord-3.0.6/lib/active_record/callbacks.rb:273:in `create_or_update'
/usr/local/rvm/gems/ree-1.8.7-2010.02@lyconic/gems/activesupport-3.0.6/lib/active_support/callbacks.rb:419:in `_run_save_callbacks'
/usr/local/rvm/gems/ree-1.8.7-2010.02@lyconic/gems/activerecord-3.0.6/lib/active_record/callbacks.rb:273:in `create_or_update'
/usr/local/rvm/gems/ree-1.8.7-2010.02@lyconic/gems/activerecord-3.0.6/lib/active_record/persistence.rb:39:in `save'
/usr/local/rvm/gems/ree-1.8.7-2010.02@lyconic/gems/activerecord-3.0.6/lib/active_record/validations.rb:43:in `save'
/usr/local/rvm/gems/ree-1.8.7-2010.02@lyconic/gems/activerecord-3.0.6/lib/active_record/attribute_methods/dirty.rb:21:in `save'
/usr/local/rvm/gems/ree-1.8.7-2010.02@lyconic/gems/activerecord-3.0.6/lib/active_record/transactions.rb:240:in `save'
/usr/local/rvm/gems/ree-1.8.7-2010.02@lyconic/gems/activerecord-3.0.6/lib/active_record/transactions.rb:292:in `with_transaction_returning_status'
/usr/local/rvm/gems/ree-1.8.7-2010.02@lyconic/gems/activerecord-3.0.6/lib/active_record/connection_adapters/abstract/database_statements.rb:139:in `transaction'
/usr/local/rvm/gems/ree-1.8.7-2010.02@lyconic/gems/activerecord-3.0.6/lib/active_record/transactions.rb:207:in `transaction'
/usr/local/rvm/gems/ree-1.8.7-2010.02@lyconic/gems/activerecord-3.0.6/lib/active_record/transactions.rb:290:in `with_transaction_returning_status'
/usr/local/rvm/gems/ree-1.8.7-2010.02@lyconic/gems/activerecord-3.0.6/lib/active_record/transactions.rb:240:in `save'
/usr/local/rvm/gems/ree-1.8.7-2010.02@lyconic/gems/activerecord-3.0.6/lib/active_record/transactions.rb:251:in `rollback_active_record_state!'
/usr/local/rvm/gems/ree-1.8.7-2010.02@lyconic/gems/activerecord-3.0.6/lib/active_record/transactions.rb:239:in `save'
/usr/local/rvm/gems/ree-1.8.7-2010.02@lyconic/gems/activerecord-3.0.6/lib/active_record/associations/association_proxy.rb:222:in `send'
/usr/local/rvm/gems/ree-1.8.7-2010.02@lyconic/gems/activerecord-3.0.6/lib/active_record/associations/association_proxy.rb:222:in `method_missing'
/var/www/88tactical_production/releases/20110823232510/app/models/purchase.rb:69:in `decrement_coupon'
:readonly => false
不保证非读取记录吗?将此功能移至优惠券模式会有所作为吗? (无论如何,我可能会这样做)
答案 0 :(得分:11)
这可能是由于您通过find_by_code()帮助程序加入其他子值。
当ActiveRecord使用连接查找返回其他值的对象时,它会将记录标记为只读。
这里有关于这个问题的详细描述:
What is causing this ActiveRecord::ReadOnlyRecord error?
如果是这种情况,您可以通过将:加入转换为正确的:include 来填充ActiveRecord实例而不标记它们,从而解决问题。仅