Related
I have two models: Connection and Membership...that have the following associations between them:
class Membership < ActiveRecord::Base
belongs_to :inviter, class_name: "User", foreign_key: "user_id"
belongs_to :invited, class_name: "User", foreign_key: "invited_id"
has_many :connections, dependent: :destroy
end
class Connection < ActiveRecord::Base
belongs_to :inviter_membership, class_name: "Membership", foreign_key: "membership_id"
belongs_to :invited_membership, class_name: "Membership", foreign_key: "invited_membership_id"
end
Here are two membership objects:
[34] pry(#<Membership>)> self
=> #<Membership id: 54, family_tree_id: 43, user_id: 41, created_at: "2015-12-01 00:40:37", updated_at: "2015-12-01 00:40:37", relation: "wife", member_id: nil, invited_id: 1, relative_type: 0>
[35] pry(#<Membership>)> mem
=> #<Membership id: 53, family_tree_id: 1, user_id: 1, created_at: "2015-12-01 00:39:58", updated_at: "2015-12-01 00:40:37", relation: "husband", member_id: nil, invited_id: 41, relative_type: 0>
[39] pry(#<Membership>)> self.invited_id
=> 1
Then I have a connection object:
[36] pry(#<Membership>)> c
=> #<Connection id: 38, membership_id: 53, sent_at: "2015-12-01 00:40:14", responded_at: nil, send_limit: nil, times_sent: 1, removed_at: nil, created_at: "2015-12-01 00:40:14", updated_at: "2015-12-01 00:40:14", request_status: 0, invited_membership_id: nil>
How do I find all the connection records, that have membership.invited_id = 41 (or some value)?
In other words, I would like to do something like this:
Connection.where("membership.invited_id = ? OR invited_membership.invited_id = ?", self.id, self.id).exists?
But when I try the above, I get this error:
[138] pry(main)> Connection.where("membership.invited_id = ? OR invited_membership.invited_id = ?", 41, 41).exists?
Connection Exists (165.3ms) SELECT 1 AS one FROM "connections" WHERE (membership.invited_id = 41 OR invited_membership.invited_id = 41) LIMIT 1
PG::UndefinedTable: ERROR: missing FROM-clause entry for table "membership"
LINE 1: SELECT 1 AS one FROM "connections" WHERE (membership.invit...
So how do I run a where query to match the column of an associated record with the parameter that I supply?
Edit 1
Based on the wonderful suggestion from #messanjah I am almost there. This is the query I am using:
Connection.joins(:inviter_membership, :invited_membership).
where("memberships.invited_id = ? OR invited_memberships_connections.invited_id = ? OR memberships.user_id = ? OR invited_memberships_connections.user_id = ?", self.inviter.try(:id), self.inviter.try(:id), self.invited.try(:id), self.invited.try(:id)).exists?
Where self is this:
[22] pry(#<Membership>)> self
=> #<Membership id: 69, family_tree_id: 49, user_id: 47, created_at: "2015-12-01 04:53:17", updated_at: "2015-12-01 04:53:17", relation: "wife", member_id: nil, invited_id: 1, relative_type: 0>
But when I run that query, it returns an empty array or false:
[14] pry(#<Membership>)> connection_exists
CACHE (0.0ms) SELECT 1 AS one FROM "connections" INNER JOIN "memberships" ON "memberships"."id" = "connections"."membership_id" INNER JOIN "memberships" "invited_memberships_connections" ON "invited_memberships_connections"."id" = "connections"."invited_membership_id" WHERE (memberships.invited_id = 47 OR invited_memberships_connections.invited_id = 47 OR memberships.user_id = 1 OR invited_memberships_connections.user_id = 1) LIMIT 1
=> false
Despite the fact that there is a memberships record with those IDs, as can be seen here:
[24] pry(#<Membership>)> c
=> #<Connection id: 49, membership_id: 68, sent_at: "2015-12-01 04:52:51", responded_at: nil, send_limit: nil, times_sent: 1, removed_at: nil, created_at: "2015-12-01 04:52:51", updated_at: "2015-12-01 04:52:51", request_status: 0, invited_membership_id: nil>
[25] pry(#<Membership>)> c.inviter_membership
=> #<Membership id: 68, family_tree_id: 1, user_id: 1, created_at: "2015-12-01 04:52:32", updated_at: "2015-12-01 04:53:17", relation: "husband", member_id: nil, invited_id: 47, relative_type: 0>
[26] pry(#<Membership>)> c.invited_membership
=> nil
[27] pry(#<Membership>)> c.inviter_membership.invited_id
=> 47
[28] pry(#<Membership>)> c.inviter_membership.user_id
=> 1
Note the IDs returned in the last two queries, yet when passed in to the main query I ran it returned empty.
What could be causing this?
Edit 2
This is the new code I am trying:
Connection.joins("LEFT JOIN memberships inviter_memberships ON inviter_memberships.id = connections.membership_id").
joins("LEFT JOIN memberships invited_memberships ON invited_memberships.id = connections.invited_membership_id").
where("inviter_memberships.invited_id = ? OR invited_memberships.invited_id = ?
OR inviter_memberships.user_id = ? OR invited_memberships.user_id = ?", self.invited.try(:id), self.invited.try(:id), self.inviter.try(:id), self.inviter.try(:id)).exists?
Where self is:
[15] pry(#<Membership>)> self
=> #<Membership id: 71, family_tree_id: 50, user_id: 48, created_at: "2015-12-01 05:46:00", updated_at: "2015-12-01 05:46:00", relation: "wife", member_id: nil, invited_id: 1, relative_type: 0>
[20] pry(#<Membership>)> self.invited
=> #<User id: 1, email: "abc#test.com", encrypted_password: "$2a$10$IQXTVqZmMaUUv4WZlwXze.OTfWki2d2qZEjj01isCZZ...", reset_password_token: nil, reset_password_sent_at: nil, remember_created_at: nil, sign_in_count: 7, current_sign_in_at: "2015-09-25 09:35:43", last_sign_in_at: "2015-09-25 01:36:10", current_sign_in_ip: "127.0.0.1", last_sign_in_ip: "192.168.1.106", created_at: "2015-07-25 02:20:15", updated_at: "2015-09-25 09:35:43", first_name: "Marc", confirmation_token: nil, confirmed_at: "2015-07-25 02:20:16", confirmation_sent_at: "2015-07-25 02:20:16", unconfirmed_email: nil, invitation_relation: nil, avatar: "Me-Bio-Pic.jpg", invitation_token: nil, invitation_created_at: nil, invitation_sent_at: nil, invitation_accepted_at: nil, invitation_limit: nil, invited_by_id: nil, invited_by_type: nil, invitations_count: 0, bio: "I am Marc Gayle. I build things and I love my fami...", last_name: "Gayle", gender: 0, birthday: nil>
[21] pry(#<Membership>)> self.inviter
=> #<User id: 48, email: "def#test.com", encrypted_password: "", reset_password_token: nil, reset_password_sent_at: nil, remember_created_at: nil, sign_in_count: 0, current_sign_in_at: nil, last_sign_in_at: nil, current_sign_in_ip: nil, last_sign_in_ip: nil, created_at: "2015-12-01 05:40:45", updated_at: "2015-12-01 05:40:45", first_name: "Cheyenne-Kari", confirmation_token: nil, confirmed_at: nil, confirmation_sent_at: nil, unconfirmed_email: nil, invitation_relation: "husband", avatar: nil, invitation_token: "D8uPGyxAeX95kfYGxRq-", invitation_created_at: "2015-12-01 05:40:45", invitation_sent_at: "2015-12-01 05:40:45", invitation_accepted_at: nil, invitation_limit: nil, invited_by_id: 1, invited_by_type: "User", invitations_count: 0, bio: nil, last_name: "Gayle", gender: 1, birthday: nil>
Basically what I am trying to do is trying to discover whether a connection record exists for the related membership record I am about to create (in an effort to not create a duplicate connection record).
In other words, each connection record, should correspond to both an inviter_membership and an invited_membership.
Right now, the connection is being created on an after_create :setup_connection callback on the Membership model. So I am trying to check the database for a Connection record that has the related membership model and then just update that connection record rather than creating a new one.
So that's why the self in my code snippets, is a membership record (because I am debugging with pry during runtime -- i.e. after the after_create has been called and before the new connection record has been created).
I hope that helps to clarify what I am trying to do. If not, I can explain some more.
Edit 3
Here is the server logs from executing the LEFT JOIN SQL I did above:
[1] pry(#<Membership>)> connection_exists
CACHE (0.0ms) SELECT 1 AS one FROM "connections" LEFT JOIN memberships inviter_memberships ON inviter_memberships.id = connections.membership_id LEFT JOIN memberships invited_memberships ON invited_memberships.id = connections.invited_membership_id WHERE (inviter_memberships.invited_id = 1 OR invited_memberships.invited_id = 1
OR inviter_memberships.user_id = 51 OR invited_memberships.user_id = 51) LIMIT 1
=> false
You can join on the associations to include their columns in a where.
Connection.joins(:inviter_membership, :invited_membership).
where("memberships.invited_id = ? OR invited_memberships_connections.invited_id = ?", self.id, self.id)
This is a little awkward because the table aliases are not obvious (I'm using Rails 4.2.3, YMMV).
You may wish to construct the joins explicitly, for greater control over the query:
Connection.
joins("INNER JOIN memberships inviter_memberships ON inviter_memberships.id = connections.inviter_membership_id").
joins("INNER JOIN memberships invited_memberships ON invited_memberships.id = connections.invited_membership_id").
where("inviter_memberships.invited_id = ?
OR invited_memberships.invited_id = ?", self.id, self.id)
If an association record may not exist (for example, a Connection may not have an invited_membership), use a LEFT join to avoid throwing it out.
Connection.
joins("LEFT JOIN memberships inviter_memberships ON inviter_memberships.id = connections.inviter_membership_id").
joins("LEFT JOIN memberships invited_memberships ON invited_memberships.id = connections.invited_membership_id").
where("inviter_memberships.invited_id = ?
OR invited_memberships.invited_id = ?", self.id, self.id)
I would like to edit a supplier name in my heroku database. I'm having trouble accessing the name attribute:
irb(main):015:0> Supplier.where(:name => "Test")
=> #<ActiveRecord::Relation [#<Supplier id: 3070, name: "Test", email: "test#me.com", phone: "555555", website: "http://www.test.co.uk", region_id: 3, category_id: 8, created_at: "2015-02-20 13:28:59", updated_at: "2015-02-20 13:28:59", rating: 0.0, address: nil, facebook_url: nil, twitter_url: nil, google_url: nil, video_url: nil, slug: "test", logo_url: nil, image_one_url: nil, image_two_url: nil, image_three_url: nil, image_four_url: nil, description: nil, reviews_count: 0, source: nil, source_other: nil>]>
irb(main):016:0> _.name
=> "Supplier"
I'm not clear why _.name is resulting in "Supplier" rather than "Test".
Can anyone tell me what I'm missing?
Supplier.where(:name => "Test") returns multiple records. Use
supplier = Supplier.where(:name => "Test").first
supplier.name
When I comment out my after_save call back, my ActiveRecord associations work just fine. In Rails Console, you'd see:
> #report = Report.create :name => "foo"
=> #<Report id: 9, name: "foo", created_at: "2013-03-05 09:51:55", updated_at: "2013-03-05 09:51:55">
> #question = #report.questions.create :description => "bar"
=> #<Question id: 18, standard_id: nil, description: "bar", element_id: nil, condition_id: nil, blueprint_name: nil, blueprint_url: nil, created_at: "2013-03-05 09:52:32", updated_at: "2013-03-05 09:52:32", additive: false, instructions: nil>
> #report.questions
=> [#<Question id: 18, standard_id: nil, description: "bar", element_id: nil, condition_id: nil, blueprint_name: nil, blueprint_url: nil, created_at: "2013-03-05 09:52:32", updated_at: "2013-03-05 09:52:32", additive: false, instructions: nil>]
> #question.reports
=> [#<Report id: 9, name: "foo", created_at: "2013-03-05 09:51:55", updated_at: "2013-03-05 09:51:55">]
However, the associations stop working when I add the following after_save callback to question.rb:
def create_matching_surveys
self.reports.each do |report|
report.reviews.each do |review|
review.competitors.each do |competitor|
competitor.surveys.find_or_create_by_question_id(self.id)
end
end
end
end
Then, in Rails Console, you get:
> #report = Report.create :name => "foo"
=> #<Report id: 13, name: "foo", created_at: "2013-03-05 10:20:51", updated_at: "2013-03-05 10:20:51">
> #question = #report.questions.create :description => "bar"
=> #<Question id: 24, standard_id: nil, description: "bar", element_id: nil, condition_id: nil, blueprint_name: nil, blueprint_url: nil, created_at: "2013-03-05 10:21:02", updated_at: "2013-03-05 10:21:02", additive: false, instructions: nil>
> #report.questions
=> [#<Question id: 24, standard_id: nil, description: "bar", element_id: nil, condition_id: nil, blueprint_name: nil, blueprint_url: nil, created_at: "2013-03-05 10:21:02", updated_at: "2013-03-05 10:21:02", additive: false, instructions: nil>]
> #question.reports
=> []
This happens whether or not the report has reviews that have competitors.
The strange thing is I thought the callback was meant to happen after the question was saved? So by rights the association should save too before any of this happens, right?
How do I fix it?
UPDATE
I think I have to call the callback in the right spot in the object's life cycle, but I can't find that spot. Here's why I think this:
> #report = Report.create :name => "foo"
=> #<Report id: 20, name: "foo", created_at: "2013-03-05 12:29:35", updated_at: "2013-03-05 12:29:35">
> #question = #report.questions.create :description => "bar"
=> #<Question id: 31, standard_id: nil, description: "bar", element_id: nil, condition_id: nil, blueprint_name: nil, blueprint_url: nil, created_at: "2013-03-05 12:30:14", updated_at: "2013-03-05 12:30:14", additive: false, instructions: nil>
> #question.reports
=> []
> #question.update_attributes :description => "foo"
=> true
> #question.reports
=> [#<Report id: 20, name: "foo", created_at: "2013-03-05 12:29:35", updated_at: "2013-03-05 12:29:35">]
BTW, the method is now in question_observer.rb:
class QuestionObserver < ActiveRecord::Observer
def after_save(model)
model.reload
model.reports.reload
model.reports.each do |report|
report.reviews.each do |review|
review.competitors.each do |competitor|
competitor.surveys.find_or_create_by_question_id(model.id)
end
end
end
return true
end
end
The answer was to use a neat new callback hook called after_commit which was introduced with Rails 3.
See http://api.rubyonrails.org/classes/ActiveRecord/Transactions/ClassMethods.html#method-i-after_commit.
The only issue is after_commit doesn't work "out of the box" with transactional fixtures, but there are plenty of solutions out there, and I found this one worked well for me: https://supportbee.com/devblog/2012/01/14/testing-after_commitafter_transaction-with-rspec/
If you look at the four method calls below, Service.first returns a Service object, Salon.first returns a Salon object, etc. But TransactionItem.first returns a Service object. Why could this be?
ruby-1.8.7-p334 :001 > Service.first
=> #<Service id: 147, name: "Fub", salon_id: 2, created_at: "2011-08-10 18:00:07", updated_at: "2011-08-10 18:00:12", price: nil, active: true, archived: true>
ruby-1.8.7-p334 :002 > Salon.first
=> #<Salon id: 1, name: "The Cheeky Strut", created_at: nil, updated_at: nil, address_id: nil, email: nil>
ruby-1.8.7-p334 :003 > Product.first
=> #<Product id: 1, name: "Herbal Essences Shampoo", retail_price: #<BigDecimal:10305f1f0,'0.1E2',9(18)>, wholesale_price: nil, sku: "", salon_id: 2, created_at: "2011-07-08 01:35:48", updated_at: "2011-07-08 01:35:48", archived: false>
ruby-1.8.7-p334 :004 > TransactionItem.first
=> #<Service id: 63, created_at: "2011-08-30 20:05:57", updated_at: "2011-08-30 20:05:57", price: #<BigDecimal:10303eba8,'0.18E2',9(18)>>
ruby-1.8.7-p334 :005 >
This is what my app/models/transaction_item.rb looks like:
class TransactionItem < ActiveRecord::Base
belongs_to :transaction
belongs_to :stylist
end
I blew away the TransactionItem table via a migration, then created a brand new migration to re-create it. That seems to have fixed the problem.
Following on from this question, I have spent the day trying to add a cumulative running sales total to my sales table. It's a bit tricky (for me) because I want a running total for sales where the isbn_id is the same, and, within that set, records where the channel_id is the same - ranked by invoice_date. This is all so I can calculate royalties on a particular range of units sold.
Here's my non-working callback code, in the Sale model:
before_save :runningtotal
private
def runningtotal
#sale = Sale.order("invoice_date ASC")
#lastbal = #sale.find_all_by_isbn_id(#isbn).group_by(&:channel)
#that sucessfully gets all sales ranked by date ascending, then groups them by channel, just for the current isbn.
#lastbal.each do |channel, sale|
sale.each_with_index do |sale, i|
previous_sale = sale[i-1] unless i==0
next unless previous_sale
#total_quantity = previous_sale.quantity + :quantity
write_attribute(:total_quantity,#total_quantity)
end
end
end
Is this roughly how a callback should be written - just in the model? Does it just run magically before_save of a new sale?
My core question is: how can I update the attribute "total_quantity" to be the sum of "quantity" for the current record, and "total_quantity" for the previous record by date, in a before_save callback, within the constraints of the finds for isbn_id and channel_id?
Here's the output of the find:
ruby-1.9.2-p180 :025 > #lastbal = #sale.find_all_by_isbn_id(#isbn).group_by(&:channel)
=> {#<Channel id: 4, isbn_id: nil, channel_name: "Gratis", created_at: "2011-05-26 11:08:22", updated_at: "2011-05-26 11:08:22">=>[#<Sale id: 26, isbn_id: 2, quantity: 10000, value: 40000, currency: "", total_quantity: nil, created_at: "2011-05-26 11:11:30", updated_at: "2011-05-26 11:11:30", customer: "6", retail_price: nil, discount: nil, channel_id: 4, invoice_date: "2011-05-18", rule_id: nil, trenche: nil>], #<Channel id: 1, isbn_id: nil, channel_name: "Home", created_at: "2011-05-16 19:47:27", updated_at: "2011-05-16 19:47:27">=>[#<Sale id: 22, isbn_id: 2, quantity: 1000, value: 5193, currency: "", total_quantity: nil, created_at: "2011-05-25 19:46:03", updated_at: "2011-05-25 19:46:03", customer: "a", retail_price: nil, discount: nil, channel_id: 1, invoice_date: "2011-05-11", rule_id: nil, trenche: nil>, #<Sale id: 24, isbn_id: 2, quantity: 1000, value: 4394, currency: "", total_quantity: nil, created_at: "2011-05-26 09:48:16", updated_at: "2011-05-26 09:48:16", customer: "g", retail_price: nil, discount: nil, channel_id: 1, invoice_date: "2011-05-10", rule_id: nil, trenche: nil>, #<Sale id: 25, isbn_id: 2, quantity: 1000, value: 4394, currency: "", total_quantity: nil, created_at: "2011-05-26 10:02:38", updated_at: "2011-05-26 10:02:38", customer: "g", retail_price: nil, discount: nil, channel_id: 1, invoice_date: "2011-05-05", rule_id: nil, trenche: nil>, #<Sale id: 21, isbn_id: 2, quantity: 1000, value: 5193, currency: "", total_quantity: nil, created_at: "2011-05-25 14:12:45", updated_at: "2011-05-25 14:12:45", customer: "a", retail_price: nil, discount: nil, channel_id: 1, invoice_date: "2010-10-15", rule_id: nil, trenche: nil>, #<Sale id: 13, isbn_id: 2, quantity: 50, value: 159, currency: "", total_quantity: nil, created_at: "2011-05-25 12:33:09", updated_at: "2011-05-25 12:33:09", customer: "a", retail_price: nil, discount: nil, channel_id: 1, invoice_date: "2010-01-01", rule_id: nil, trenche: nil>, #<Sale id: 14, isbn_id: 2, quantity: 25, value: 129, currency: "", total_quantity: nil, created_at: "2011-05-25 12:33:23", updated_at: "2011-05-25 12:33:23", customer: "", retail_price: nil, discount: nil, channel_id: 1, invoice_date: "2010-01-01", rule_id: nil, trenche: nil>, #<Sale id: 12, isbn_id: 2, quantity: 100, value: 415, currency: "", total_quantity: nil, created_at: "2011-05-25 12:32:50", updated_at: "2011-05-25 15:13:21", customer: "a", retail_price: nil, discount: nil, channel_id: 1, invoice_date: "2001-10-01", rule_id: nil, trenche: nil>, #<Sale id: 11, isbn_id: 2, quantity: 500, value: 2197, currency: "", total_quantity: nil, created_at: "2011-05-25 12:32:24", updated_at: "2011-05-25 15:11:20", customer: "a", retail_price: nil, discount: nil, channel_id: 1, invoice_date: "2000-10-01", rule_id: nil, trenche: nil>], #<Channel id: 2, isbn_id: nil, channel_name: "Export", created_at: "2011-05-16 19:47:35", updated_at: "2011-05-16 19:47:35">=>[#<Sale id: 23, isbn_id: 2, quantity: 2000, value: 5000, currency: "", total_quantity: nil, created_at: "2011-05-26 09:16:15", updated_at: "2011-05-26 09:16:15", customer: "v", retail_price: nil, discount: nil, channel_id: 2, invoice_date: "2011-05-02", rule_id: nil, trenche: nil>, #<Sale id: 17, isbn_id: 2, quantity: 242, value: 657, currency: "", total_quantity: nil, created_at: "2011-05-25 12:34:24", updated_at: "2011-05-25 12:34:24", customer: "b ", retail_price: nil, discount: nil, channel_id: 2, invoice_date: "2010-10-15", rule_id: nil, trenche: nil>, #<Sale id: 18, isbn_id: 2, quantity: 54, value: 194, currency: "", total_quantity: nil, created_at: "2011-05-25 12:34:44", updated_at: "2011-05-25 12:34:44", customer: "b ", retail_price: nil, discount: nil, channel_id: 2, invoice_date: "2010-10-15", rule_id: nil, trenche: nil>, #<Sale id: 15, isbn_id: 2, quantity: 135, value: 377, currency: "", total_quantity: nil, created_at: "2011-05-25 12:33:48", updated_at: "2011-05-25 12:33:48", customer: "b ", retail_price: nil, discount: nil, channel_id: 2, invoice_date: "2010-09-15", rule_id: nil, trenche: nil>, #<Sale id: 16, isbn_id: 2, quantity: 433, value: 830, currency: "", total_quantity: nil, created_at: "2011-05-25 12:34:06", updated_at: "2011-05-25 12:34:06", customer: "b ", retail_price: nil, discount: nil, channel_id: 2, invoice_date: "2010-09-15", rule_id: nil, trenche: nil>]}
Here's the columns in my Sale model:
# id :integer not null, primary key
# isbn_id :integer
# quantity :integer
# value :integer
# currency :string(255)
# total_quantity :integer
# created_at :datetime
# updated_at :datetime
# customer :string(255)
# retail_price :integer
# discount :decimal(, )
# channel_id :integer
# invoice_date :date
# rule_id :integer
Thanks so much in advance.
UPDATE: final solution.
Really not sure that this counts as 'giving back to the community' as it's comically verbose, not DRY, full of puts which I used to figure out all the bugs, and badly formatted to boot, but heck, I'm a noob at and the very least I can come back here and laugh at myself in a few years when I know what I'm doing. So, here's my final solution, in Sale.rb. Poor overstuffed model. I will refactor this, one day.
before_save :runningtotal
after_commit :refresh
private
def runningtotal
# get the latest sale that matches the new sale's isbn and channel id, then rank by invoice date descending, and get the first record:
lastsale = Sale.where(:isbn_id => self.isbn_id).where(:channel_id => self.channel_id).order("invoice_date DESC").first
allsales = Sale.where(:isbn_id => self.isbn_id).where(:channel_id => self.channel_id).order("invoice_date DESC")
# set the total_quantity field in the new sales record to its quantity + the last sale's total.
if allsales.maximum(:invoice_date).nil?
puts "runningtotal thinks the max of invoice date in the allsales relation is nil"
puts "and runningtotal is setting total_quantity on the new sale to be #{self.quantity + (lastsale.try(:total_quantity) || 0)}"
self.total_quantity = self.quantity + (lastsale.try(:total_quantity) || 0)
else
if self.invoice_date < allsales.maximum(:invoice_date)
puts "the runningtotal method has been skipped because runningtotal thinks the current invoice date is less than the highest invoice date in the allsales relation"
else
puts "this is a normal entry so runningtotal has set the total quantity to be #{self.quantity + (lastsale.try(:total_quantity) || 0) }"
self.total_quantity = self.quantity + (lastsale.try(:total_quantity) || 0)
end
end
end
def refresh
allsales = Sale.where(:isbn_id => self.isbn_id).where(:channel_id => self.channel_id).order("invoice_date ASC")
#if the runningtotal callback hasn't run, the total quantity will be nil, and nil triggers this after_commit callback
if total_quantity.nil?
puts "running refresh callback"
puts "here's a sample parameter pass: id: #{id} quantity: #{quantity} date: #{invoice_date} "
puts "allsales class is #{allsales.class}"
# if the new sale that's being saved has a date that's before any previous sale...
puts "before the if, refresh thinks that the earliest invoice date is #{allsales.minimum(:invoice_date)} and that invoice date is #{invoice_date}"
if invoice_date <= allsales.minimum(:invoice_date)
puts "date earlier than existing sales dates"
puts "refresh thinks that the earliest invoice date is #{allsales.minimum(:invoice_date)} and that invoice date is #{invoice_date}"
#... then set its total_quantity to the sale quantity...
update_attribute(:total_quantity, quantity)
puts "total_qty updated with qty"
# ... and update all subsequent records' total_quantity (skipping the before_save callback which would trigger an infinite loop).
allsales.each_with_index do |sale, i|
previous_sale = allsales[i-1] unless i==0
next unless previous_sale
puts "getting qty out of arel when date earlier than others: #{previous_sale.quantity}"
puts "this is adding #{quantity} to #{previous_sale.quantity } which is #{quantity + previous_sale.total_quantity }"
Sale.skip_callback(:save, :before, :runningtotal )
sale.update_attribute(:total_quantity, (sale.quantity + previous_sale.total_quantity ))
Sale.set_callback(:save, :before, :runningtotal)
end
else
# if the invoice date is within the min and max range of the previous sales...
# ... update all previous and subsequent records' total_quantity (skipping the before_save callback which would trigger an infinite loop).
allsales.each_with_index do |sale, i|
previous_sale = allsales[i-1] unless i==0
next unless previous_sale
puts "getting qty out of arel within existing date range: #{previous_sale.quantity}"
puts "this is adding #{quantity} to #{previous_sale.quantity } which is #{quantity + previous_sale.total_quantity }"
Sale.skip_callback(:save, :before, :runningtotal )
sale.update_attribute(:total_quantity, (sale.quantity + previous_sale.total_quantity ))
Sale.set_callback(:save, :before, :runningtotal )
end
end
end
end
Yes, using before_save in the model will run that every time it is saved, whether new or updated. Thus you need to watch out in calculations the expect the current (new) record to not exist yet. ;) You might want to use before_save, :on => :create to limit it to the creation action.
However, if I understand your english statement of the problem, your code is rather convoluted. I don't even see where #isbn is set, that could be dangerous...
Does this need to update the total on other objects this isbn and channel? Usually it's better form to simply calculate that as needed rather than trying to cache the total in every record.
within the callback, self is the current (new?) record, so use it to refer to new values.
#sale = Sale.order("invoice_date ASC")
#lastbal = #sale.find_all_by_isbn_id(#isbn).group_by(&:channel)
can be replaced by this, I think:
#lastbal = Sale.order("invoice_date ASC").where(:isbn_id => self.isbn_id).group_by(&:channel)
I'm assuming that #isbn is actually the new record's isbn.
From there, I'm not sure if you are only intending to update the new record or the old ones... If you want to update the current record, just set the attribute and exit the callback, and it will be saved when the rest is saved:
self.total_quantity = previous_sale.quantity + self.quantity
If you are intending to update the other objects too, then we have to update those objects and save them. I don't see that happening at all here in your code.
Your code goes through several loops, possibly hitting the write_attribute several times... that doesn't make sense.
If you mean you want to find the last record that matches the current isbn and channel to update the new record, here's what I would do:
def runningtotal
lastsale = Sale.where(:isbn_id => self.isbn_id).
where(:channel_id => self.channel_id).
order("invoice_date DESC").first
# that should be the latest sale that matches
# the current isbn and channel
self.total_quantity = self.quantity + (lastsale.try(:total_quantity) || 0)
# watch out for nil if no previous record exists ^
end
`