Using Rails 3. I have the following:
# shop.rb
class Shop < ActiveRecord::Base
belongs_to :country, :touch => true, :counter_cache => :total_shops
...
end
# shops_controller.rb
class ShopsController < ApplicationController
def create
...
#shop.save
#new_total_shops = #country.total_shops
end
end
Let's say initial #country.total_shops is 2, then when it's created, it should be incremented to 3, but when I try abort(#country.total_shops) right after the line #shop.save, it still shows 2. When I refresh the page, it shows 3. I guess it just gets updated a bit slow.
How can I get the latest value quickly?
Thanks.
My guess is that since you've (I assume) already loaded the Country instance before you save the new shop, you're seeing the total_shops value as it was when the country was loaded.
I.e. you've got the old value in memory, even though the underlying database values have changed.
Try this:
#shop.save
# reload the country instance from the database
# to get the updated counter cache value
#country.reload
#new_total_shops = #country.total_shops
Related
Recent days , I was trying to cache rails app use Redis store.
I have two models:
class Category < ActiveRecord::Base
has_many :products
after_save :clear_redis_cache
private
def clear_redis_cache
puts "heelllooooo"
$redis.del 'products'
end
end
and
class Product < ActiveRecord::Base
belongs_to :category, touch: true
end
in controller
def index
#products = $redis.get('products')
if #products.nil?
#products = Product.joins(:category).pluck("products.id", "products.name", "categories.name")
$redis.set('products', #products)
$redis.expire('products', 3.hour.to_i)
end
#products = JSON.load(#products) if #products.is_a?(String)
end
With this code , the cache worked fine.
But when I updated or created new product (I have used touch method in relationship) it's not trigger after_save callback in Category model.
Can you explain me why ?
Have you read documentation for touch method?
Saves the record with the updated_at/on attributes set to the current
time. Please note that no validation is performed and only the
after_touch, after_commit and after_rollback callbacks are executed.
If an attribute name is passed, that attribute is updated along with
updated_at/on attributes.
If you want after_save callbacks to be executed when calling touch on some model, you can add
after_touch :save
to this model.
If you set the :touch option to :true, then the updated_at or updated_on timestamp on the associated object will be set to the current time whenever this object is saved or destroyed
this the doc :
http://guides.rubyonrails.org/association_basics.html#touch
You can also (at least in rails 6) just use after_touch: callback
From the docs:
after_touch: Registers a callback to be called after a record is touched. See ActiveRecord::Callbacks for more information.
I am pretty new to rails (and development) and have a requirement to create a change log. Let's say you have an employees table. On that table you have an employee reference number, a first name, and a last name. When either the first name or last name changes, I need to log it to a table somewhere for later reporting. I only need to log the change, so if employee ref 1 changes from Bill to Bob, then I need to put the reference number and first name into a table. The change table can have all the columns that mnight change, but most only be populated with the reference number and the changed field. I don't need the previous value either, just the new one. hope that makes sense.
Looked at gems such as paper trail, but they seem very complicated for what I need. I don't ever need to manipulate the model or move versions etc, I just need to track which fields have changed, when, and by whom.
I'd appreciate your recommendations.
If you insist on building your own changelog, based on your requirements you can do so using a few callbacks. First create your log table:
def up
create_table :employee_change_logs do |t|
t.references :employee
# as per your spec - copy all column definitions from your employees table
end
end
In your Employee model:
class Employee < ActiveRecord::Base
has_many :employee_change_logs
before_update :capture_changed_columns
after_update :log_changed_columns
# capture the changes before the update occurs
def capture_changed_columns
#changed_columns = changed
end
def log_changed_columns
return if #changed_columns.empty?
log_entry = employee_change_logs.build
#changed_columns.each{|c| log_entry.send(:"#{c}=", self.send(c))}
log_entry.save!
end
end
I recommend the gem vestal_versions.
To version an ActiveRecord model, simply add versioned to your class like so:
class User < ActiveRecord::Base
versioned
validates_presence_of :first_name, :last_name
def name
"#{first_name} #{last_name}"
end
end
And use like this:
#user.update_attributes(:last_name => "Jobs", :updated_by => "Tyler")
#user.version # => 2
#user.versions.last.user # => "Tyler"
The first thing we did was put an around filter in the application controller. This was how I get the current_employee into the employee model, which was the challenge, especially for a newbie like me!
around_filter :set_employee_for_log, :if => Proc.new { #current_account &&
#current_account.log_employee_changes? && #current_employee }
def set_employee_for_log
Thread.current[:current_employee] = #current_employee.id
begin
yield
ensure
Thread.current[:current_employee ] = nil
end
end
end
Next, in the employee model I defined which fields I was interested in monitoring
CHECK_FIELDS = ['first_name', 'last_name', 'middle_name']
then I added some hooks to actually capture the changes IF logging is enabled at the account level
before_update :capture_changed_columns
after_update :log_changed_columns, :if => Proc.new { self.account.log_employee_changes? }
def capture_changed_columns
#changed_columns = changed
#changes = changes
end
def log_changed_columns
e = EmployeeChangeLog.new
Employee::CHECK_FIELDS.each do |field|
if self.send("#{field}_changed?")
e.send("#{field}=", self.send(field))
end
end
if e.changed?
e.update_attribute(:account_id, self.account.id)
e.update_attribute(:employee_id, self.id)
e.update_attribute(:employee_ref, self.employee_ref)
e.update_attribute(:user_id, Thread.current[:current_employee])
e.save
else return
end
end
And that;s it. If the account enables it, the app keeps an eye on specific fields and then all changes to those fields are logged to a table, creating an simple audit trail.
I'm trying to use the before_validation callback to adjust the number of child objects for a record, but for some reason, its not working the way I expect.
LineItem class:
before_validation :adjust_enrollment_count
def adjust_enrollment_count
if enrollments.size < quantity
(enrollments.size+1..quantity).each do |li|
self.enrollments.build(variant: self.variant)
end
#self.save
elsif enrollments.size > quantity
enrollments.delete_if do |e|
enrollments.size > quantity
end
end
end
What happens is that it creates the correct number of Enrollment objects as children to the LineItem, but the Variant gets set to nil (even though the LineItem has a variant defined).
Things I've tried:
Explicitly saving the line_item or the enrollment
"pry"ing into the callback and running the code manually (this actually worked the way
I expected!)
Verifying that "self" referred to the LineItem and not the closure
Is there something about the callback lifecycle that I'm missing? Is there a better way to adjust the number of Enrollment objects as the quantity changes on the LineItem?
Probably variant is not an accessible field of the Enrollment class. Try this way (also shortened)
def adjust_enrollment_count
while enrollments.size < quantity
self.enrollments.build(variant_id: self.variant) # note: variant_id
end
while enrollments.size > quantity
enrollments.pop # or .shift to delete from the head of the list
end
# don't save in a lifecycle callback, or you'll get in an awful loop
end
EDIT: a different take
def add_enrollment
enrollments.build(variant_id: variant)
end
def adjust_enrollment_count
enrollments.slice!(quantity, enrollments.size)
add_enrollment while enrollments.length < quantity
end
It turned out that the problem was something that I didn't have outlined in my question. I had defined the following:
class Enrollment < ActiveRecord::Base
belongs_to :line_item
attr_accessible :variant
attr_accessor :variant
end
I think the attr_accessor was creating an in-memory variable called variant that only lasted as long as the page load. I removed that and it seemed to solve the problem.
Using Rails 3.1.3 and I'm trying to figure out why our counter caches aren't being updated correctly when changing the parent record id via update_attributes.
class ExhibitorRegistration < ActiveRecord::Base
belongs_to :event, :counter_cache => true
end
class Event < ActiveRecord::Base
has_many :exhibitor_registrations, :dependent => :destroy
end
describe ExhibitorRegistration do
it 'correctly maintains the counter cache on events' do
event = Factory(:event)
other_event = Factory(:event)
registration = Factory(:exhibitor_registration, :event => event)
event.reload
event.exhibitor_registrations_count.should == 1
registration.update_attributes(:event_id => other_event.id)
event.reload
event.exhibitor_registrations_count.should == 0
other_event.reload
other_event.exhibitor_registrations_count.should == 1
end
end
This spec fails indicating that the counter cache on event is not being decremented.
1) ExhibitorRegistration correctly maintains the counter cache on events
Failure/Error: event.exhibitor_registrations_count.should == 0
expected: 0
got: 1 (using ==)
Should I even expect this to work or do I need to manually track the changes and update the counter myself?
From the fine manual:
:counter_cache
Caches the number of belonging objects on the associate class through the use of increment_counter and decrement_counter. The counter cache is incremented when an object of this class is created and decremented when it’s destroyed.
There's no mention of updating the cache when an object is moved from one owner to another. Of course, the Rails documentation is often incomplete so we'll have to look at the source for confirmation. When you say :counter_cache => true, you trigger a call to the private add_counter_cache_callbacks method and add_counter_cache_callbacks does this:
Adds an after_create callback which calls increment_counter.
Adds an before_destroy callback which calls decrement_counter.
Calls attr_readonly to make the counter column readonly.
I don't think you're expecting too much, you're just expecting ActiveRecord to be more complete than it is.
All is not lost though, you can fill in the missing pieces yourself without too much effort. If you want to allow reparenting and have your counters updated, you can add a before_save callback to your ExhibitorRegistration that adjusts the counters itself, something like this (untested demo code):
class ExhibitorRegistration < ActiveRecord::Base
belongs_to :event, :counter_cache => true
before_save :fix_counter_cache, :if => ->(er) { !er.new_record? && er.event_id_changed? }
private
def fix_counter_cache
Event.decrement_counter(:exhibitor_registration_count, self.event_id_was)
Event.increment_counter(:exhibitor_registration_count, self.event_id)
end
end
If you were adventurous, you could patch something like that into ActiveRecord::Associations::Builder#add_counter_cache_callbacks and submit a patch. The behavior you're expecting is reasonable and I think it would make sense for ActiveRecord to support it.
If your counter has been corrupted or you've modified it directly by SQL, you can fix it.
Using:
ModelName.reset_counters(id_of_the_object_having_corrupted_count, one_or_many_counters)
Example 1: Re-compute the cached count on the post with id = 17.
Post.reset_counters(17, :comments)
Source
Example 2: Re-compute the cached count on all your articles.
Article.ids.each { |id| Article.reset_counters(id, :comments) }
I recently came across this same problem (Rails 3.2.3). Looks like it has yet to be fixed, so I had to go ahead and make a fix. Below is how I amended ActiveRecord::Base and utilize after_update callback to keep my counter_caches in sync.
Extend ActiveRecord::Base
Create a new file lib/fix_counters_update.rb with the following:
module FixUpdateCounters
def fix_updated_counters
self.changes.each {|key, value|
# key should match /master_files_id/ or /bibls_id/
# value should be an array ['old value', 'new value']
if key =~ /_id/
changed_class = key.sub(/_id/, '')
changed_class.camelcase.constantize.decrement_counter(:"#{self.class.name.underscore.pluralize}_count", value[0]) unless value[0] == nil
changed_class.camelcase.constantize.increment_counter(:"#{self.class.name.underscore.pluralize}_count", value[1]) unless value[1] == nil
end
}
end
end
ActiveRecord::Base.send(:include, FixUpdateCounters)
The above code uses the ActiveModel::Dirty method changes which returns a hash containing the attribute changed and an array of both the old value and new value. By testing the attribute to see if it is a relationship (i.e. ends with /_id/), you can conditionally determine whether decrement_counter and/or increment_counter need be run. It is essnetial to test for the presence of nil in the array, otherwise errors will result.
Add to Initializers
Create a new file config/initializers/active_record_extensions.rb with the following:
require 'fix_update_counters'
Add to models
For each model you want the counter caches updated add the callback:
class Comment < ActiveRecord::Base
after_update :fix_updated_counters
....
end
A fix for this has been merged in to active record master
https://github.com/rails/rails/issues/9722
The counter_cache function is designed to work through the association name, not the underlying id column. In your test, instead of:
registration.update_attributes(:event_id => other_event.id)
try
registration.update_attributes(:event => other_event)
More information can be found here: http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html
I'm writing a little browser game as a project to learn RoR with and I'm quite new to it.
This is a little method that's called regularly by a cronjob.
I'm guessing there should be some way of adding elements to the potions array and then doing a bulk save at the end, I'm also not liking hitting the db each time in the loop to get the number of items for the market again.
def self.restock_energy_potions
market = find_or_create_market
potions = EnergyPotion.find_all_by_user_id(market.id)
while (potions.size < 5)
potion = EnergyPotion.new(:user_id => market.id)
potion.save
potions = EnergyPotion.find_all_by_user_id(market.id)
end
end
I'm not sure I'm understanding your question. Are you looking for something like this?
def self.restock_energy_potions
market = find_or_create_market
potions = EnergyPotion.find_all_by_user_id(market.id)
(potions.size...5).each {EnergyPotion.new(:user_id => market.id).save }
end
end
Note the triple dots in the range; you don't want to create a potion if there are already 5.
Also, if your potions were linked (e.g. by has_many) you could create them through the market.potions property (I'm guessing here, about the relationship between users and markets--details depend on how your models are set up) and save them all at once. I don't think the data base savings would be significant though.
Assuming that your market/user has_many potions, you can do this:
def self.restock_energy_potions
market = find_or_create_market
(market.potions.size..5).each {market.potions.create(:user_id => market.id)}
end
a) use associations:
class Market < AR::Base
# * note that if you are not dealing with a legacy schema, you should
# rename user_id to market_id and remove the foreigh_key assignment.
# * dependent => :destroy is important or you'll have orphaned records
# in your database if you ever decide to delete some market
has_many :energy_potions, :foreign_key => :user_id, :dependent => :destroy
end
class EnergyPotion < AR::Base
belongs_to :market, :foreign_key => :user_id
end
b) no need to reload the association after adding each one. also move the functionality
into the model:
find_or_create_market.restock
class Market
def restock
# * note 4, not 5 here. it starts with 0
(market.energy_potions.size..4).each {market.energy_potions.create!}
end
end
c) also note create! and not create.
you should detect errors.
error handling depends on the application.
in your case since you run it from cron you can do few things
* send email with alert
* catch exceptions and log them, (exception_notifier plugin, or hoptoad hosted service)
* print to stderror and configuring cron to send errors to some email.
def self.restock_potions
market = find_or_create
market.restock
rescue ActiveRecord::RecordInvalid
...
rescue
...
end