rufus gem how to keep one job running while stopping the other - ruby-on-rails

This is my scheduler.rb in my initializer file
unless defined?(Rails::Console) || File.split($0).last == 'rake'
s = Rufus::Scheduler.singleton
s.every '1m', :tag => 'main_process' do
Rails.logger.info "hello, it's #{Time.now}"
Rails.logger.flush
Bid.all.each do |bid|
id = bid.event_id
puts "*" * 50
puts bid.id
puts bid.event_id
puts "*" * 50
# #price = BuyNowBid.find_by(bid_id: params[:bid_id])
#events = Unirest.get("https://api.seatgeek.com/2/events/#{id}?&client_id=NjQwNTEzMXwxNDgxNDkxODI1").body
if #events["stats"]
#low = #events["stats"]["lowest_price"] || 0
#avg = #events["stats"]["average_price"] || 0
BuyNowBid.create(bid_id: bid.id, lowest_price: #low , average_price: #avg)
if #low <= bid.bid
send_message("+13125501444", "Lowest price matched! Buy your ticket now!")
bid.bid = 0
bid.save
end
else
puts 'problem with #events?'
p #events
end
end
end
end
def send_message(phone_number, alert_message)
account_sid = ""
auth_token = ""
#client = Twilio::REST::Client.new account_sid, auth_token
#twilio_number = ""
message = #client.messages.create(
:from => #twilio_number,
:to => phone_number,
:body => alert_message
)
puts message.to
end
so I'm running a job to pull the lowest price every minute from an api and when the lowest price matches a bid someones placed they receive a text notification, which works although, the problem I'm having is i want the job to keep running where ever minute I'm pulling the lowest price from api, but i don't want the user to keep getting the same text notification every minute.
Right now I have it so this doesn't happen but after a bid is matched it is essentially deleted from the database. so basically I'm asking how can I keep scraping the api every minute for the lowest price bid match but only send one text to the user notifying them of the bid match and to not have to delete that bid from the database.

I was really over thinking this i just created a new column called saved bid on my bid table and set that equal to bid.bid before it became zero
#events = Unirest.get("https://api.seatgeek.com/2/events/#{id}?&client_id=NjQwNTEzMXwxNDgxNDkxODI1").body
if #events["stats"]
#low = #events["stats"]["lowest_price"] || 0
#avg = #events["stats"]["average_price"] || 0
BuyNowBid.create(bid_id: bid.id, lowest_price: #low , average_price: #avg)
if #low <= bid.bid
send_message("+13125501444", "Lowest price matched for #{#events["title"]} ! Buy your ticket now for #{bid.saved_bid}!")
**bid.saved_bid = bid.bid**
bid.bid = 0
bid.save

Related

Scraping data in rails using thread

I am doing scraping to fetch the data from the website to my database in rails.I am fetching the 32000 record with this script there isn't any issue but i want to fetch the data faster so i apply the thread in my rake task but then there is a issue while running the rake task some of the data is fetching then the rake task getting aborted.
I am not aware of what to do task if any help can be done i am really grateful . Here is my rake task code for the scraping.
task scratch_to_database: :environment do
time2 = Time.now
puts "Current Time : " + time2.inspect
client = Mechanize.new
giftcard_types=Giftcard.card_types
find_all_merchant=Merchant.all.pluck(:id, :name).to_h
#first index page of the merchant
index_page = client.get('https://www.twitter.com//')
document_page_index = Nokogiri::HTML::Document.parse(index_page.body)
#set all merchant is deteled true
# set_merchant_as_deleted = Merchant.update_all(is_deleted: true) if Merchant.exists?
# set_giftcard_as_deleted = Giftcard.update_all(is_deleted: true) if Giftcard.exists?
update_all_merchant_record = []
update_all_giftcard_record = []
threads = []
#Merchant inner page pagination loop
page_no_merchant = document_page_index.css('.pagination.pagination-centered ul li:nth-last-child(2) a').text.to_i
1.upto(page_no_merchant) do |page_number|
threads << Thread.new do
client.get("https://www.twitter.com/buy-gift-cards?page=#{page_number}") do |page|
document = Nokogiri::HTML::Document.parse(page.body)
#Generate the name of the merchant and image of the merchant loop
document.css('.product-source').each do |item|
merchant_name= item.children.css('.name').text.gsub("Gift Cards", "")
href = item.css('a').first.attr('href')
image_url=item.children.css('.img img').attr('data-src').text.strip
#image url to parse the url of the image
image_url=URI.parse(image_url)
#saving the record of the merchant
# #merchant=Merchant.create(name: merchant_name , image_url:image_url)
if find_all_merchant.has_value?(merchant_name)
puts "this if"
merchant_id=find_all_merchant.key(merchant_name)
puts merchant_id
else
#merchant= Merchant.create(name: merchant_name , image_url:image_url)
update_all_merchant_record << #merchant.id
merchant_id=#merchant.id
end
# #merchant.update_attribute(:is_deleted, false)
#set all giftcard is deteled true
# set_giftcard_as_deleted = Giftcard.where(merchant_id: #merchant.id).update_all(is_deleted: true) if Giftcard.where(merchant_id: #merchant.id).exists?
#first page of the giftcard details page
first_page = client.get("https://www.twitter.com#{href}")
document_page = Nokogiri::HTML::Document.parse(first_page.body)
page_no = document_page.css('.pagination.pagination-centered ul li:nth-last-child(2) a').text.to_i
hrefextra =document_page.css('.dropdown-menu li a').last.attr('href')
#generate the giftcard details loop with the pagination
# update_all_record = []
find_all_giftcard=Giftcard.where(merchant_id:merchant_id).pluck(:row_id)
puts merchant_name
# puts find_all_giftcard.inspect
card_page = client.get("https://www.twitter.com#{hrefextra}")
document_page = Nokogiri::HTML::Document.parse(card_page.body)
#table details to generate the details of the giftcard with price ,per_off and final value of the giftcard
document_page.xpath('//table/tbody/tr[#class="toggle-details"]').collect do |row|
type1=[]
row_id = row.attr("id").to_i
row.at("td[2] ul").children.each do |typeli|
type = typeli.text.strip if typeli.text.strip.length != 0
type1 << type if typeli.text.strip.length != 0
end
value = row.at('td[3]').text.strip
value = value.to_s.tr('$', '').to_f
per_discount = row.at('td[4]').text.strip
per_discount = per_discount.to_s.tr('%', '').to_f
final_price = row.at('td[5] strong').text.strip
final_price = final_price.to_s.tr('$', '').to_f
type1.each do |type|
if find_all_giftcard.include?(row_id)
update_all_giftcard_record<<row_id
puts "exists"
else
puts "new"
#giftcard= Giftcard.create(card_type: giftcard_types.values_at(type.to_sym)[0], card_value:value, per_off:per_discount, card_price: final_price, merchant_id: merchant_id , row_id: row_id )
update_all_giftcard_record << #giftcard.row_id
end
end
#saving the record of the giftcard
# #giftcard=Giftcard.create(card_type:1, card_value:value, per_off:per_discount, card_price: final_price, merchant_id: #merchant.id , gift_card_type: type1)
end
# Giftcard.where(:id =>update_all_record).update_all(:is_deleted => false)
#delete all giftcard which is not present
# giftcard_deleted = Giftcard.where(:is_deleted => true,:merchant_id => #merchant.id).destroy_all if Giftcard.where(merchant_id: #merchant.id).exists?
time2 = Time.now
puts "Current Time : " + time2.inspect
end
end
end
end
threads.each(&:join)
puts "-------"
puts threads
# merchant_deleted = Merchant.where(:is_deleted => true).destroy_all if Merchant.exists?
merchant_deleted = Merchant.where('id NOT IN (?)',update_all_merchant_record).destroy_all if Merchant.exists?
giftcard_deleted = Giftcard.where('row_id NOT IN (?)',update_all_giftcard_record).destroy_all if Giftcard.exists?
end
end
Error i am receiving:
ActiveRecord::ConnectionTimeoutError: could not obtain a connection from the pool within 5.000 seconds (waited 5.001 seconds); all pooled connections were in use
Each thread requires a separate connection to your database. You need to increase the connection pool size that your application can use in your database.yml file.
But your database should also be capable of handling the incoming connections. If you are using mysql you can check this by running select ##MAX_CONNECTIONS on your console.

Filter created_at with 3 functions by parsing DateTime rails

currently i am getting values from database with a query
created_ats = Snapshot.connection.select_all("SELECT created_at from snapshots WHERE snapshot_id >= '#{camera_id}_#{from_date}' AND snapshot_id <= '#{camera_id}_#{to_date}'")
This query is giving me all created_ats according to conditions.
i want to filter all these created_ats according to some inputs which users have been passed to database which are
days and times
"{"Monday":["3:0-7:0","15:0-17:30"],"Tuesday":[],"Wednesday":["11:0-16:0"],"Thursday":["5:0-10:0"],"Friday":["15:30-22:30"],"Saturday":[],"Sunday":[]}"
its just an example days and times are can be totally filled or partially.
there is a field named as INTERVAL. which is being considered as MINUTES.
Now what is the whole scenario, from query i am getting created_at which is general timestamps in ruby on rails.
i want to filter those created_at with the giving Days and timings provided along with everyday in info above. + adding X(interval) to that created at as well.
such as after refining between days and timings. we will have a list of created_ats so after that starting from first created_at will add x.minutes in that created at and will assure that (created_at+x.minutes) is also present in created_ats(which we got after days and hours refining), is YESS then save it else leave it.
what i have tried so far is this and its not working as i want it to work according to me it seems no error in that but still dont give me specific value
class SnapshotExtractor < ActiveRecord::Base
establish_connection "evercam_db_#{Rails.env}".to_sym
belongs_to :camera
require "rmega"
require "aws-sdk-v1"
require 'open-uri'
def self.connect_mega
storage = Rmega.login("#{ENV['MEGA_EMAIL']}", "#{ENV['MEGA_PASSWORD']}")
storage
end
def self.connect_bucket
access_key_id = "#{ENV['AWS_ACCESS_KEY']}"
secret_access_key = "#{ENV['AWS_SECRET_KEY']}"
s3 = AWS::S3.new(
access_key_id: access_key_id,
secret_access_key: secret_access_key,
)
bucket = s3.buckets["evercam-camera-assets"]
bucket
end
# def self.test
# snapshot_bucket = connect_bucket
# storage = connect_mega
# folder = storage.root.create_folder("dongi")
# s3_object = snapshot_bucket.objects["gpo-cam/snapshots/1452136326.jpg"]
# snap_url = s3_object.url_for(:get, {expires: 1.years.from_now, secure: true}).to_s
# File.open("formula.txt", 'w') { |file| file.write(snap_url) }
# open('image.jpg', 'wb') do |file|
# file << open(snap_url).read
# end
# folder.upload("image.jpg")
# end
def self.extract_snapshots
running = SnapshotExtractor.where(status: 1).any?
unless running
#snapshot_request = SnapshotExtractor.where(status: 0).first
#snapshot_request.update_attribute(:status, 1)
camera_id = #snapshot_request.camera_id
exid = Camera.find(camera_id).exid
mega_id = #snapshot_request.id
from_date = #snapshot_request.from_date.strftime("%Y%m%d")
to_date = #snapshot_request.to_date.strftime("%Y%m%d")
interval = #snapshot_request.interval
#days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
set_days = []
set_timings = []
index = 0
#days.each do |day|
if #snapshot_request.schedule[day].present?
set_days[index] = day
set_timings[index] = #snapshot_request.schedule[day]
index += 1
end
end
begin
created_ats = Snapshot.connection.select_all("SELECT created_at from snapshots WHERE snapshot_id >= '#{camera_id}_#{from_date}' AND snapshot_id <= '#{camera_id}_#{to_date}'")
created_at_spdays = refine_days(created_ats, set_days)
created_at_sptime = refine_times(created_at_spdays, set_timings, set_days)
created_at = refine_intervals(created_at_sptime, interval)
File.open("test.txt", 'w') { |file| file.write(created_at) }
storage = connect_mega
creatp = storage.root.create_folder("created_at")
creatp.upload("test.txt")
rescue => error
notify_airbrake(error)
end
begin
storage = connect_mega
snapshot_bucket = connect_bucket
new_folder = storage.root.create_folder("#{exid}")
folder = storage.nodes.find do |node|
node.type == :folder and node.name == "#{exid}"
end
folder.create_folder("#{mega_id}")
created_at.each do |snap|
snap_i = DateTime.parse(snap).to_i
s3_object = snapshot_bucket.objects["#{exid}/snapshots/#{snap_i}.jpg"]
if s3_object.exists?
snap_url = s3_object.url_for(:get, {expires: 1.years.from_now, secure: true}).to_s
File.open("formula_#{snap_i}.txt", 'w') { |file| file.write(snap_url) }
open('#{snap_i}.jpg', 'wb') do |file|
file << open(snap_url).read
end
folder.upload('#{snap_i}.jpg')
end
end
#snapshot_request.update_attribute(:status, 3)
rescue => error
error
end
end
# created_at
end
private
def self.refine_days(created_ats, days)
created_at = []
index = 0
created_ats.each do |single|
days.each do |day|
if day == Date.parse(single["created_at"]).strftime("%A")
created_at[index] = single["created_at"]
index += 1
end
end
end
created_at
end
def self.refine_times(created_ats, timings, days)
created_at = []
index = 0
day_index = 0
days_times = days.zip(timings.flatten)
one = 1
zero = 0
created_ats.each do |single|
days_times.each do |day_time|
if Date.parse(single).strftime("%A") == day_time[day_index]
start_time = DateTime.parse(day_time[one].split("-")[zero]).strftime("%H:%M")
end_time = DateTime.parse(day_time[one].split("-")[one]).strftime("%H:%M")
created_at_time = DateTime.parse(single).strftime("%H:%M")
if created_at_time >= start_time && created_at_time <= end_time
created_at[index] = single
index += 1
end
end
end
end
created_at
end
def self.refine_intervals(created_ats, interval)
created_at = [created_ats.first]
last_created_at = DateTime.parse(created_ats.last)
index = 1
index_for_dt = 0
length = created_ats.length
(1..length).each do |single|
if (DateTime.parse(created_at[index_for_dt]) + interval.minutes) <= last_created_at
temp = DateTime.parse(created_at[index_for_dt]) + interval.minutes
created_at[index] = temp.to_s
index_for_dt += 1
index += 1
end
end
created_at
end
end

Aggregate an array of Merchant store hours that overlap to produce a single range

I have a list of store hours from a merchant that could potentially overlap stored in AvailableHours model. The model has a start_time and an end_time stored as a TimeOfDay object (https://github.com/JackC/tod).
I want to iterate through the list and compare the store hours so that I can just display 1 store hour. For example, if a store could had hours of Mon: 9am-2pm and Mon: 10am-5pm, I would want to display Mon: 9am-5pm. A store could also have two times in a single day, i.e. Fri: 9-5pm, 7pm-10pm. I have to do this for each day of the week.
The issue I am running into is that my code is becoming hard to manage - I started introducing a lot of nested if/else for manual checking (what a nightmare!), but my question is this:
Is there a way to use ActiveRecord to produce a hash with merged time ranges?
def ranges_overlap?(shift, current_shift)
shift.include?(current_shift.beginning) || current_shift.include?(shift.beginning)
end
def merge_ranges(shift, current_shift)
new_open_time = [shift.beginning, current_shift.beginning].min
new_close_time = [shift.ending, current_shift.ending].max
Shift.new(new_open_time, new_close_time)
end
def get_aggregate_merchant_hours
merchant = self
day = nil
shifts_array = []
output_shift_array = []
merchant_shifts = merchant_shifts = merchant.available_hours.order(day: :asc, open_time: :desc).map do |ah|
merged_shift = nil
show_output = false
# if it's a new day
if day.blank? || day != ah.day
output_shift_array = shifts_array
shifts_array = []
show_output = true if !day.blank?
output_day = day
day = ah.day
end
next if ah.open_time.blank? || ah.close_time.blank?
open_time = ah.open_time
close_time = ah.close_time
current_shift = Shift.new(open_time, close_time)
if !shifts_array.blank?
#compare and merge
shifts_array.each do |shift|
merged_shift = merge_ranges(shift, current_shift) if ranges_overlap?(shift, current_shift)
end
end
#replace old shift with merged shift
if merged_shift
delete_shift = shifts_array.find(beginning: current_shift.beginning, ending: current_shift.ending).first
shifts_array.delete(delete_shift) if delete_shift
shifts_array.push(merged_shift)
else
shifts_array.push(current_shift)
end
if show_output
store_hours_string = ""
if output_shift_array.blank?
store_hours_string = "Closed"
else
output_shift_array.each do |shift|
shift.beginning.strftime("%I:%M%p")
shift.ending.strftime("%I:%M%p")
if store_hours_string.blank?
store_hours_string << "#{shift.beginning.strftime("%I:%M%p").downcase} - #{shift.ending.strftime("%I:%M%p").downcase}"
else
store_hours_string << ", #{shift.beginning.strftime("%I:%M%p").downcase} - #{shift.ending.strftime("%I:%M%p").downcase}"
end
end
end
"#{Date::DAYNAMES[output_day][0..2]}: #{store_hours_string}"
end
end
#output last shift
store_hours_string = ""
if output_shift_array.blank?
store_hours_string = "Closed"
else
output_shift_array.each do |shift|
shift.beginning.strftime("%I:%M%p")
shift.ending.strftime("%I:%M%p")
if store_hours_string.blank?
store_hours_string << "#{shift.beginning.strftime("%I:%M%p").downcase} - #{shift.ending.strftime("%I:%M%p").downcase}"
else
store_hours_string << ", #{shift.beginning.strftime("%I:%M%p").downcase} - #{shift.ending.strftime("%I:%M%p").downcase}"
end
end
end
merchant_shifts << "#{Date::DAYNAMES[day][0..2]}: #{store_hours_string}"
merchant_shifts.compact
end

Cant found model with out an ID in rails 3.2.12

i ve this method. I m not at all able to understand the error which is
Couldn't find Company without an ID
in ActiveRecord::RecordNotFound in CustomersController#bulk_create
This method is written to create customers for a company in bulk by taking their name and numbers in format name:number.
The method is as follows:
def bulk_create
res = ""
comp_id = params[:customer][:selected_companies].delete_if{|a| a.blank?}.first
comp = Company.find(comp_id)
s = SentSmsMessage.new
s.set_defaults
s.data = tmpl("command_signup_ok", customer, comp) unless params[:customer][:email].length > 0
s.data = params[:customer][:email] if params[:customer][:email].length > 0
s.company = comp if !comp.nil?
s.save
unless comp_id.blank?
params[:customer][:name].lines.each do |line|
(name, phone) = line.split(/\t/) unless line.include?(":")
(name, phone) = line.split(":") if line.include?(":")
phone = phone.gsub("\"", "")
phone = phone.strip if phone.strip.to_i > 0
name = name.gsub("\"", "")
name = name.gsub("+", "")
phone = "47#{phone}" if params[:customer][:active].to_i == 1
customer = Customer.first(:conditions => ["phone_number = ?", phone])
if customer.nil?
customer = Customer.new
customer.name = name
# customer.email
# customer.login
# customer.password
customer.accepted_agreement = DateTime.now
customer.phone_number = phone
customer.active = true
customer.accepted_agreement = DateTime.now
customer.max_msg_week = params[:customer][:max_msg_week]
customer.max_msg_day = params[:customer][:max_msg_day]
customer.selected_companies = params[:customer][:selected_companies].delete_if{|a| a.blank?}
res += "#{name} - #{phone}: Create OK<br />" if customer.save
res += "#{name} - #{phone}: Create failed<br />" unless customer.save
else
params[:customer][:selected_companies].each do |cid|
new_company = Company.find(cid) unless cid.blank?
if !new_company.nil?
if !customer.companies.include?(new_company)
customer.companies << new_company
if customer.save
res += "#{name} - #{phone}: Customer exists and the customer was added to the firm #{new_company.name}<br />"
else
res += "#{name} - #{phone}: Customer exist, but something went wrong during storage. Check if the client is in the firm.<br />"
end
else
res += "#{name} - #{phone}: Customer exists and is already on firm #{new_company.name}<br />"
end
end
end
end
s.sms_recipients.create(:phone_number => customer.phone_number)
end
s.save
s.send_as_sms
#result = res
respond_to do |format|
format.html { render "bulk_create"}
end
else
#result = "You have not selected any firm to add these users. Press the back button and try again."
respond_to do |format|
format.html { render "bulk_create"}
end
end
end
I want to update one situation here. That when i submit the form blank then it gives this error. Also if i filled the form with the values then its show the situation which the method is returning in case of fail.
res += "#{name} - #{phone}: Create failed <br />"
The tmpl method
private
def tmpl(setting_name, customer, company = nil)
text = ""
if customer.companies.count > 0
sn = "#{setting_name}_#{#customer.companies.first.company_category.suffix}".downcase rescue setting_name
text = Setting.value_by(sn) rescue ""
end
textlenth = text.length rescue 0
if textlenth < 3
text = Setting.value_by(setting_name) rescue Setting.value_by("command_error")
end
return fill_template(text, customer, company)
end
From the model customer.rb
def selected_companies=(cmps)
cmps.delete("")
# Check the old ones. Make a note if they are not in the list. If the existing ones are not in the new list, just remove them
self.companies.each do |c|
self.offer_subscriptions.find(:first, ["customer_id = ?", c]).destroy unless cmps.include? c.id.to_s
cmps.delete c.id.to_s if cmps.include? c.id.to_s
end
# Then create the new ones
cmps.each do |c2|
cmp = Company.find(:first, ["id = ?", c2])
if cmp && !c2.blank?
offerSubs = offer_subscriptions.new
offerSubs.company_id = c2
offerSubs.save
end
end
end
def selected_companies
return self.companies.collect{|c| c.id}
end
The association of customer is as follows:
has_many :offer_subscriptions
has_many :companies, :through => :offer_subscriptions
This code is written by the some one else. I m trying to understand this method but so far not being able to understand this code.
Please help.
Thanks in advance.
You are getting 'Couldn't find Company without an ID' error because your Company table doesn't contain record with id = comp_id
Change comp = Company.find(comp_id) to comp = Company.find_by_id(comp_id).
This will return nil instead of an error.
Add comp is not nil condition is already handled in your code.
Your comp_id line is returning nil.
comp_id = params[:customer][:selected_companies].delete_if{|a| a.blank?}.first
Post the params that get passed to this function and we could hopefully find out why. In the meantime you could enclose the block in a begin - rescue block to catch these errors:
begin
<all your code>
rescue ActiveRecord::RecordNotFound
return 'Unable to find a matching record'
end
try this:
comp = ""
comp = Company.find(comp_id) unless comp_id.nil?
instead of comp = Company.find(comp_id)
further nil checking present in your code.
Reason being
params[:customer][:selected_companies].delete_if{|a| a.blank?} = []
so [].first = nil
therefor, params[:customer][:selected_companies].delete_if{|a| a.blank?}.first = nil
and comp_id is nil
So check the log file and check what is coming in the parameter "selected_companies"
when you will find the parameter, everything will be understood well....

Ruby on rails rake task not returning up-to-date model info

While building a billing system I encountered the following problem:
In scheduler.rake :
#users.each do |user|
begin
puts "CALCULATING COSTS =========="
costs = user.total_billable_price_per_month(Time.now)
lead_count = user.total_billable_leads_count(Time.now)
click_count = user.total_billable_clicks_count(Time.now)
puts "CREATING NEW INVOICES ======="
#invoice = user.invoices.new
# if user.free_credits
# invoice.total_price_in_cents = 0
# else
# invoice.total_price_in_cents = costs.cents
# end
#invoice.total_leads = lead_count
#invoice.total_clicks = click_count
#invoice.total_price_in_cents = costs.cents
# Als de vorige factuur onder de 10 euro was, dan geld bij huidige factuur optellen
if user.invoices.last && user.invoices.last.total_price_in_cents < 1000
puts "Bedrag onder 10 euro"
puts "Last invoice = #{user.invoices.last.total_price_in_cents}"
#invoice.total_price_in_cents += user.invoices.last.total_price_in_cents
end
puts "SAVING INVOICE FOR #{user.name} with ID = #{user.id}"
# Factuur saven
#invoice.save
#Als de factuur hoger of gelijk is als 10euro, dan factuur aanmaken
if #invoice.total_price_in_cents >= 1000
#Moneybird factuur versturen
puts "COSTS ARE HIGHER THAN 10 EURO, CREATING MONEYBIRD INVOICE"
moneybird_invoice = MoneybirdInvoice.new
sleep(15)
moneybird_invoice.contact_id = MoneybirdContact.find_by_customer_id(user.id).id
sleep(15)
moneybird_invoice.details_attributes = [
{ :description => "Aantal leads", :amount => lead_count, :price => user.lead_price.cents.to_f/100},
{ :description => "Aantal clicks", :amount => click_count, :price => user.click_price.cents.to_f/100}
]
puts "TRYING TO SAVE MONEYBIRD INVOICE"
if moneybird_invoice.save && moneybird_invoice.put(:send_invoice)
puts "SUCCESFULLY SAVED INVOICE"
#GET UPDATED PAY URL
#sent_mb_invoice = MoneybirdInvoice.get(moneybird_invoice.id)
sleep(15)
#invoice.update_attributes(:moneybird_invoice_id => #sent_mb_invoice['invoice_id'], :moneybird_pay_url => #sent_mb_invoice['pay_url'])
else
puts "MONEYBIRD INVOICE FAILED"
puts moneybird_invoice.errors.inspect
end
else
# GEEN MONEYBIRD FACTUUR AANMAKEN
end
rescue
puts "ER IS IETS FOUT GEGAAN MET FACTUREREN USER ID = #{user.id} & NAME = #{user.name}"
puts #invoice.errors.inspect
end
end
This piece of code should constantly increment each time the rake task is run, except when the total amount reaches > 1000.
if user.invoices.last && user.invoices.last.total_price_in_cents < 1000
puts "Bedrag onder 10 euro"
puts "Last invoice = #{user.invoices.last.total_price_in_cents}"
#invoice.total_price_in_cents += user.invoices.last.total_price_in_cents
end
The code above always puts "Last invoice = 100" => This should increment each time the rake tasks is run
Every new invoice still has the same total_price_in_cents (when I'm expecting that it should increment).
What is going on ?
EDIT: Added after code upadte:
In your updated code, it looks like you were calling user.invoices.last after you called user.invoices.new, this is why it always returned the same value.
Create a variable #last_invoice = user.invoices.last before call user.invoices.new.
ORIGINAL ANSWER:
In your original code posting, it looks like your save call on #invoice happened outside the loop -- I believe you're only saving it once.
task :create_invoices => :environment do
# Begin the loop for each use
User.all.each do |user|
#invoice = user.invoices.build
#If last bill < 1000
if user.invoices.last && user.invoices.last.total_price_in_cents < 1000
puts "Last invoice = #{user.invoices.last.total_price_in_cents}"
#invoice.total_price_in_cents += user.invoices.last.total_price_in_cents
#invoice.save
end # end 'if' statement
end # end loop for all users
end # end task definition
So you loop though the users table, but never save updates -- except for the very last time after you exit the loop

Resources