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

I know "all" isn't an integer
I took this method of the official documentation postgres + rails (I can't link it now but might later if needed)
def list
#a = a.find(:all)
end
so I thought it would list every "a" in "a" table, but didn't. Instead that error was thrown. Isn't this the way rails+gres works? Help a newbie please, thank you vm

find accepts an integer and finds the record with the given int ID.
If you want to retrieve all records, use:
def list
#a = A.all
end
Assuming that A is a model

Related

Rails - Querying a JSON Field

In my Rails 5 app, I'm using the Ahoy gem which uses a jsonb field (called properties) that I don't know how to query.
A sample of the data in the properties field:
"{\"id\":\"11\"}"
What I'm trying to do is:
Find the records created in the last seven days (using the time field)
Group the records by the id in the properties field
Order the records based on which id had the most records
I tried this:
#foo = Ahoy::Event.where(name: "Viewed Product").where(time: 7.days.ago..Time.now).group("properties(id)").order('COUNT("properties(id)") DESC')
but I received the error, PG::UndefinedColumn: ERROR: column "properties(id)" doe not exist
I found this somewhat similar question in the issues for the gem, so I tried breaking the query into parts:
#foo = Ahoy::Event.where(name: "Viewed Product").where(time: 7.days.ago..Time.now)
#foo.group("properties REGEXP '[{,]\"id\"...).count
but then my IDE gives the error unterminated string meets the end of file.
Can someone please help me determine what I'm doing wrong?
If you are using PostgreSQL, I believe that you would have to refer to json columns like this:
.group("properties ->> 'id'")

How to define dynamic variable and assign it to some value in rails

I want to create dynamic variable and assign values to them. Here is quick sample what I tried so far.
array = %w(this is a test)
array.each_with_index do |c,v|
puts "variable_#{v}".to_sym
end
which gives me output like this:
# variable_0
# variable_1
# variable_2
# variable_3
But when I am trying to assign value like below:
array.each_with_index do |c,v|
puts "variable_#{v}".to_sym = 45 # I want to assign value which will be result of api, here I just pass 45 static
end
this gives me an error:
undefined method `to_sym=' for "variable_0":String (NoMethodError)
If I removed .to_sym it gives me an error like:
syntax error, unexpected '='
Please help me. How can I achieve this? Thanks in advance.
Note: This is just a sample code to understand how to create dynamic variables and assign them variable. In my app it's a instance_variable and I want to use them to achieve my goal.
Considering that you really need to set instance variable dynamically, instance_variable_set may help you.
array.each_with_index do |c,v|
instance_variable_set "#variable_#{v}".to_sym, 45 # `#` indicates instance variable
end
You can collect result in array or hash. Its difficult to give example with partial info. But in array you can collect result as follows:
result_set = array.collect do |c|
45
end
Which will give you
result_set = ["this", "is", "a", "test"]
For hash let me know what type of key and value you want to collect so that I can give you particular example.
I hope this will help you.

How do you access an object's (ActiveRecord::Relation) value by key in Ruby on Rails?

tl;dr How do I get the corresponding value with the key of an object?
I'm confused why
Atag.where(tag:'brand') gives me what I would call an object for lack of a better term: #<ActiveRecord::Relation [#<Atag id: 1, tag: "brand", created_at: "2015-01-31 04:29:20", updated_at: "2015-01-31 04:29:20">]>
But I'm having the basic difficult of accessing the corresponding value for the key :id.
Atag.where(tag:'brand').id and Atag.where(tag:'brand')[:id] and Atag.where(tag:'brand')(:id) all throw errors, while in this case I'm just trying to have the integer 1 returned.
I seem to be unable to ruby, nor find a succinct answer to this basic question with my google searching skills (or lack there of).
Thanks
From great documentation at the Odin Project.
The key thing to note is that #find returns the actual record while #where returns an ActiveRecord::Relation which basically acts like an array.
So if you're using #where to find a single record, you still need to remember to go into that "array" and grab the first record, e.g. User.where(:email => "foo#bar.com")[0] or User.where(:email => "foo#bar.com").first.
This gets me all the time...
Get the id of your tag = 'brand' with following query:
Atag.find_by(tag:'brand').id
Check following variations:
Atag.find(1)
#gives you the object with the Atag id = 1
Atag.find(100) #let's say this record does not exist then you will
get ActiveRecord::RecordNotFound exception.
Better option :
Atag.where(id: 1)
#this returns you a relation and it's true you are trying to access
only a single object.
Hence, you just need to modify it to :
Atag.where(id: 1).first
#Above one will give you an object of Atag not an association result.
# to verfiy you can execute, Atag.where(id: 1).first.class
Atag.where(id: 999).first
# In this case if there is no record found with id = 999, then it'll
return nil which can be easily handled than an exception found
while using find method.
Get the same flavor using the dynamic finders.
Atag.find_by(id: 1) #gives the Atag with id 1
Atag.find_by_id(1). # same as above.
Atag.find_by(id: 999) #if not found then simply returns nil.
Atag.find_by(name: 'ruby') #return Atag object with name: 'ruby'
Atag.find_by_name('ruby') #same as above.
Yep, looks like you figured it out. For reference, you can use Atag.where(tag:'brand').first to get the first result, and Atag.where(tag:'brand').to_a to get an array of all the matching results.
where return instance of ActiveRecord::Relation which can be treated like an array with records as its members. Even if the result is single it should be accessed like a member of array with single element
Atag.where(tag: 'brand')
returns the array of results and to access id we should get the record from the array first i.e.
Atag.where(tag: 'brand')[0].id
In order to get id of all the matching records we need to use pluck with where. pluck returns an array of attribute that is plucked.
Atag.where(tag: 'brand').pluck(:id)
This would return an array of id from the collection returned by where only.
The find_by method finds the first record matching some conditions. Since find_by returns the record (not an array) , we can do:
Atag.find_by(tag: 'brand').id
PS: No one had mentioned pluck that's why I wrote this answer. Hope its helpful.

How to find the minimum value in a table column in Rails 3

Hi lets say I have a table(ads) with a column(views)
Views
2
1
4
6
3
How do I find the smallest value in this column? Any easy way to do this?
This is what I have
#ads = Ad.all
#show_this_ad = #ads.min(:views)
this gives me a "wrong number of arguments(1 for 0) error"
#ads = Ad.all
#show_this_ad = #ads.minimum(:views)
this gives me a "undefined method error"
Ad.minimum(:views)
should work
You can still add more restrictions like:
Ad.where(:user_id => 12345).minimum(:views)
To find only adds by the user with id 12345
btw: You can easily test such things in the rails console (just type "rails c" from the commandline)
One thing that often helps me is just to get the class of the result of some operation.
If you enter something like:
#foo = Add.all
And then:
#foo.class
You will see, that #foo is an array, which of course doesn't know anything of ActiveRecord#minimum

Rails: Getting column value from query

Seems like it should be able to look at a simple tutorial or find an aswer with a quick google, but I can't...
codes = PartnerCode.find_by_sql "SELECT * from partner_codes where product = 'SPANMEX' and isused = 'false' limit 1"
I want the column named code, I want just the value. Tried everything what that seems logical. Driving me nuts because everything I find shows an example without referencing the actual values returned
So what is the object returned? Array, hash, ActiveRecord? Thanks in advance.
For Rails 4+ (and a bit earlier I think), use pluck:
Partner.where(conditions).pluck :code
> ["code1", "code2", "code3"]
map is inefficient as it will select all columns first and also won't be able to optimise the query.
You need this one
Partner.where( conditions ).map(&:code)
is shorthand for
Partner.where( conditions ).map{|p| p.code}
PS
if you are often run into such case you will like this gem valium by ernie
it gives you pretty way to get values without instantiating activerecord object like
Partner.where( conditions ).value_of :code
UPDATED:
if you need access some attribute and after that update record
save instance first in some variable:
instance=Partner.where( conditions ).first
then you may access attributes like instance.code and update some attribute
instance.update_attribute || instance.update_attributes
check documentation at api.rubyonrails.org for details

Resources