PG::InvalidTextRepresentation: ERROR: invalid input syntax for integer - ruby-on-rails

I am doing a "IN" query using prepared statements on rails. I am getting PG::InvalidTextRepresentation error.
code :
def mark_ineligible(match_ids)
ids = match_ids.join(", ")
result = epr("mark_matches_as_ineligible",
"UPDATE matches SET is_eligibile=false WHERE id IN ( $1 )",
[ids])
end
def epr(statementname, statement, params)
connection = ActiveRecord::Base.connection.raw_connection
begin
result = connection.exec_prepared(statementname, params)
return result
rescue PG::InvalidSqlStatementName => e
begin
connection.prepare(statementname, statement)
rescue PG::DuplicatePstatement => e
# ignore since the prepared statement already exists
end
result = connection.exec_prepared(statementname, params)
return result
end
end
trying to invoke this using :
match_ids = [42, 43]
mark_ineligible match_ids
PG::InvalidTextRepresentation: ERROR: invalid input syntax for integer: "42, 43"
from (irb):24:in `exec_prepared'
from (irb):24:in `rescue in epr'
from (irb):15:in `epr'
from (irb):8:in `mark_ineligible'
from (irb):35
Please help here. I want to know why I am getting this errors and how to fix it.
Thanks,

mark_ineligible should look as follows:
def mark_ineligible(match_ids)
result = epr("mark_matches_as_ineligible",
"UPDATE matches SET is_eligibile=false WHERE id IN ( $1 )", match_ids)
end
And when you call mark_ineligible, pass an array as argument:
mark_ineligible(match_ids) #=>match_ids = [42,43]

Related

Ruby webapplication, getting "wrong number of arguments (given 3, expected 2)" error

I made some changes in one of the controllers in our webapp. Essentially, the controller was sending out an email to the customer if the order was cancelled, and changed the status of the order in the database. This is how it originally the snippet looked like:
elsif #ac == "mino"
begin
#wifi_order = WifiOrder.find(params["id"])
ApplicationMailer.cancelled_mino(#wifi_order, WifiUser.find_by(email: #wifi_order.email), 10000).deliver_now
#wifi_order = WifiOrder.find(params["id"])
#wifi_order.order_status = "status_cancelled_pending_fees"
#wifi_order.order_status_sub = "status_cancelled_force"
#wifi_order.cancelled_at = DateTime.now
#wifi_order.payment_next = nil
#wifi_order.confirm = nil
#wifi_order.save!
rescue => e
p e.message
flash[:error] = e.message
return
end
This is what I changed it for, because I wanted to send two different kinds of emails depending on the payment method set:
elsif #ac == "mino"
begin
#wifi_order = WifiOrder.find(params["id"])
if #wifi_order.pay_type = "card"
ApplicationMailer.cancelled_mino(#wifi_order, WifiUser.find_by(email: #wifi_order.email), 10000).deliver_now
else
ApplicationMailer.cancelled_mino_paid(#wifi_order, WifiUser.find_by(email: #wifi_order.email), 10000).deliver_now
end
#wifi_order = WifiOrder.find(params["id"])
#wifi_order.order_status = "status_cancelled_pending_fees"
#wifi_order.order_status_sub = "status_cancelled_force"
#wifi_order.cancelled_at = DateTime.now
#wifi_order.payment_next = nil
#wifi_order.confirm = nil
#wifi_order.save!
rescue => e
p e.message
flash[:error] = e.message
return
end
Ever since the changes, when I try to test it, I get this error:
wrong number of arguments (given 3, expected 2)
What did I do wrong?
Why it is happening
The wrong number of arguments you are getting hints at the solution.
It details a method is expecting 2 arguments while you are sending 3.
def say_hello(first_name, last_name)
puts "#{first_name} #{last_name}"
end
say_hello("John", "Doe") # -> will work
say_hello("John", "Von", "Doe") # -> will raise wrong number of arguments error
How to fix it
At first sight, it seems that the method you've added cancelled_mino_paid is the cause of the wrong number of arguments error.
You can fix it in one of two ways:
when defining the cancelled_mino_paid method, make sure it can receive 3 arguments
only send 2 arguments when calling the cancelled_mino_paid method

ActionView::Template::Error (can't convert Symbol into Integer)

Doing one iteration with a hash in ruby, but some times in production(only on production) getting this symbol error.
Controller
#d1 = Model.get_driver_details
Model
def get_driver_details
driver_det = Hash.new
driver_det[:driver_details] = Table.select('name as d_name, SUM(total) as
total_count').group('driver.id')
end
Result
{:driver_details=>[{:d_name=>"Tomy", :total_count=>"25"}]}
Iteration
total_count = 0
#d1[:driver_details].each do |driver|
total_count += driver[:total_count].to_f
end
So i am getting this error ActionView::Template::Error (can't convert Symbol into Integer) in this line #d1[:driver_details].each do |driver|
This method is not returning the driver_det hash, it's only returning one entry in the hash and that entry is an array. (so it expects an integer for indexing, hence the error)
def get_driver_details
driver_det = Hash.new
driver_det[:driver_details] = Table.select('name as d_name, SUM(total) as
total_count').group('driver.id')
end
If you return the hash (reference it in the last line), you'll be ok.
def get_driver_details
driver_det = Hash.new
driver_det[:driver_details] = Table.select('name as d_name, SUM(total) as
total_count').group('driver.id')
driver_det
end
I assume you plan to support other keys in future?

Parsing the text file in ruby

My text file looks like this
VOTE 1168041805 Campaign:ssss_uk_01B Validity:during Choice:Antony CONN:MIG01TU MSISDN:00777778359999 GUID:E6109CA1-7756-45DC-8EE7-677CA7C3D7F3 Shortcode:63334
VOTE 1168041837 Campaign:ssss_uk_01B Validity:during Choice:Leon CONN:MIG00VU MSISDN:00777770939999 GUID:88B52A7B-A182-405C-9AE6-36FCF2E47294 Shortcode:63334
I want to get value of vote campaign validity choice for which I am doing this:
File.foreach('lib/data/file.txt') do |line|
line = line.tidy_bytes
begin
aline = line.match(/^VOTE\s(\d+)\sCampaign:([^ ]+)\sValidity:([^ ]+)\sChoice:([^ ]+)/)
unless aline.nil?
## do something
end
rescue Exception => e
raise " error: " + e.inspect
p line.inspect
next
end
end
Is there any better way for doing this for
aline = line.match(/^VOTE\s(\d+)\sCampaign:([^ ]+)\sValidity:([^ ]+)\sChoice:([^ ]+)/)
and getting aline[1] aline[2] aline[3] and aline[4]
You can use named captures to get a hash of results instead:
# use a freezed contant instead of making a new Regexp object for each line
REGEXP = /^VOTE\s(?<id>\d+)\sCampaign:(?<campaign>[^ ]+)\sValidity:(?<validity>[^ ]+)\sChoice:(?<choice>[^ ]+)/.freeze
File.foreach('lib/data/file.txt') do |line|
begin
matches = line.tidy_bytes.match(REGEXP)
hash = matches.names.zip(matches.captures).to_h
end
rescue Exception => e
raise " error: " + e.inspect
p line.inspect
next
end
end
If the desired result is an array you might want to use .map:
# use a freezed contant instead of making a new Regexp object for each line
REGEXP = /^VOTE\s(?<id>\d+)\sCampaign:(?<campaign>[^ ]+)\sValidity:(?<validity>[^ ]+)\sChoice:(?<choice>[^ ]+)/.freeze
results = File.foreach('lib/data/file.txt').map do |line|
matches = line.tidy_bytes.match(REGEXP)
matches.names.zip(matches.captures).to_h
end

Ruby or Rails: PG Data Query Error,

I'm trying to update a few records based on a user entered string - it won't let me and produces this error:
PGError: ERROR: invalid input syntax for type boolean: "ian"
LINE 1: UPDATE "subjects" SET treatment_group = 'ian' AND pref_rand ...
I double checked the type from the rails console:
Subject.column_hash["treatment_group"].type
=> :string
And the input method is:
Group Name: <%= text_field_tag(:treatment_group_name) %>
Finally, within the controller I have this logic:
#group_to_randomize = Subject.where("study_site = ? AND treatment_group is null", params[:site_input].to_i).order("created_at ASC").limit(params[:group_size_input].to_i)
flash[:notice] = "We are at the database level. #{#group_to_randomize.inspect}"
if params[:treatment_group_name] != '' and params[:site_input] != '' and params[:group_size_input] != ''
#group_to_randomize.update_all(["treatment_group = ? AND pref_rand = ?", params[:treatment_group_name, #treatment.to_i])
flash[:notice] = "Subjects randomized, and assigned to group #{params[:treatment_group_name]}"
else
flash[:notice] = "Nothing saved, please fill in the form completely."
end
So that it's easier to read, the error stems from this line:
#group_to_randomize.update_all(["treatment_group = ? AND pref_rand = ?", params[:treatment_group_name], #treatment.to_i])
So I can't figure out why it thinks the input is a boolean, and why it won't save as a string anyway. Any help would be greatly appreciated.
because of syntax error, modify this line
#group_to_randomize.update_all(treatment_group:params[:treatment_group_name], pref_rand: #treatment.to_i)

Ruby on Rails array delete_if block, string is "missing translation: no key" inside but fine outside

My problem is that the print t inside the delete_if block prints 'translation missing: en.no key'
This is strange. The error message in the browser shows me my pages parameters.
Here is what is says for tutor_id:
"tutor_id"=>["1", "2"].
I also tried the following inside the block to make sure it was right, and it did indeed return String.
print t.class # => returns 'String'
Also making a call to the following inside the block yields an error
Integer(t) # => yields error: invalid value for Integer(): "translation missing: en.no key"
Likewise, a call to .to_i is not helpful. It always returns 0. Note: this is the behavior o any non-numerical string such as 'hello'.to_s
print t.to_i # always prints '0'
The following is the troublesome code:
#get an array of all tutors' IDs
tutorIds = params[:tutor_id]
tutorIds.delete_if { [t]
print t
Schedule.exists?(["tutor_id = ?", Integer(t)])
}
Update I left out a bit of information so if the delete_if block is
tutorIds.delete_if { [t]
print t
Schedule.exists?(["tutor_id = ?", t ])
}
The error I get is:
PG::InvalidTextRepresentation: ERROR: invalid input syntax for integer: "translation missing: en.no key" LINE 1: ...ECT 1 AS one FROM "schedules" WHERE (tutor_id = 'translati... ^ : SELECT 1 AS one FROM "schedules" WHERE (tutor_id = 'translation missing: en.no key') LIMIT 1
Well it was right under my nose. Such a simple mistake. Notice the [] -> ||
tutorIds.delete_if { [t]
print t
Schedule.exists?(["tutor_id = ?", t ])}
Should have been
tutorIds.delete_if { |t|
print t
Schedule.exists?(["tutor_id = ?", t ])}
Can you try
Schedule.where("tutor_id = ?", t.to_i).exists?
instead?

Resources