Rails 3.1 - find using count and select as - ruby-on-rails

I am trying to do the following sql statement in rails:
SELECT COUNT(downloads.title) AS total, downloads.title FROM `downloads` WHERE `downloads`.`member_id` = 60 Group by `downloads`.`title`
I wrote this in rails like this:
Download.where(:member_id => id).select("COUNT(downloads.title) AS total, downloads.title").group(:title)
If I run the query straight from the sql server the sql executes correctly but if I run the activerecord version I only get the title back.
I thought this might be because of attr_accessible but this doesnt seem to have made a difference.
any ideas ?

Have you tried to call total method on the collection object ?
This information is not included in the output for object using to_s method, so you probably just do not see it, but total value is there.
downloads = Download.where(:member_id => id).select("COUNT(downloads.title) AS total, downloads.title").group(:title)
downloads.first.total

Related

Delete from database with specific details in ruby

I try to delete from database all row has a id include in some array or (key,value)
"recp" => "1, 2, 3 , 6, 7 , ........."
ID in #recipient
I try this:
#v = NameOfDatabase.where.not(:id=> #recipient.split(',').map(&:to_i), :conditions => {:thread =>#dis_PI.m_id}).destroy_all
With specific condition i want to remove row with this condition and not include in #recipient
Error in this method :
NoMethodError (undefined method `where' for #<Class:0x7f447f57b140>):
I try multiple code but not working, i put this question multiple time but also not work yet!
From the comments, I learned that you are running a very old version of Ruby on Rails – probably more than 10 years old. With Rails 3.0 the finder methods change completely and therefore all current documentation for Rails will not be helpful anymore. Especially the where method did not exist before Rails 3.0
In such an old version the following should work:
YourModel.destroy_all("id in (?)", #recipient.split(','))
Here you will find the docs of older Rails versions.
The condition is basically just one SQL fragment. When you want to add more conditions then you need to write all conditions in one line like this:
YourModel.destroy_all(
"id IN (?) AND thread = ?", #recipient.split(','), #dis_PI.m_id
)

Active record create query in multiple steps

I'm a bit confused by active record, it just seems to fire the query at any time you stop, ie.
#model.where( :store_id => #sid )
Which is fine, but what if I want to build a query like this:
query = #model.where( :store_id => #sid )
if(some_condition)
query.offset(50)
and then execute the query (not actually what I'm doing but a very simple example). Is there a way to put together the query in steps and then tell it to execute?
Actually, ActiveRecord will do exactly what you want. It's called lazy loading. You might be getting confused by the rails console, which calls .inspect behinds the scenes on the result of the line.
Check out this question: Lazy loading in Rails 3.2.6
This already works like you want it too.
where() returns an instance of ActiveRecord::Relation.
The relation won't execute it's database call until it needs to. The reason you might be experiencing otherwise is that you're testing it in the console, which prints the output of each statement (thus loading the relation). You can test whether a relation has been loaded via the loaded() method.
Try this on the console:
m = #model.where(:store_id => #sid); # the semicolon will silence the output
m.loaded? # nil
m # executes db call, will print out the contents of the relation
m.loaded? # true

Using Rails ActiveRecord to Query Unsaved Objects

Is it possible to query unsaved changes using Rail's ActiveRecord or another similar approach?
An example of a Ruby interactive session is below. What I'd like to see, is the fourth line show a result of '999' instead of '10'. I'm use to using .NET and Entity Framework where something similar to this was possible. Perhaps in Ruby there is a better or different way to do the same thing. I could obviously add up the sum in a loop, but I find the query syntax more elegant. Any help is appreciated.
i = Inventory.where(:product_id => 1)
i.sum(:available) => 10
i.first.available = 999
i.sum(:available) => 10
No, since sum() is actually translated to SQL and run on the db, you must save the record to the db in order for the query to return the result you want.
Alternatively, you can use the Enumerable#sum method in ActiveSupport, which takes a block, like so:
all = Inventory.where(:product_id => 1).to_a
all.first.available = 999
all.sum(&:available)

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

stop meta_search doing sql to early

in the docs it's said:
MyObject.search()
returns an instance of MetaSearch::Builder (something like ActiveRecord::Relation). But in my case when I do this I get a collection of objects because the sql-query is send to the database.
I would like to have something like this:
search = MyObject.search() # no sql-query should be done here
count = search.count # count sql done
objects = search.all # select sql done - maybee with pagination
does anyone know how to stop Meta_search from doing the the query to early?
-> ok, something mysterious going on in my shell:
search = MyObject.search() # queries the database
search = MyObject.search(); 0 # stores a MetaSearch-Object in search
the console seems to call an extra method after each comand
If you're testing in irb, be aware that returned objects are inspected. In the case of a MetaSearch builder, this means the relation gets inspected. If you have a look at ActiveRecord's inspect method, in relation.rb, you'll see that it calls to_a, which executes the query and returns the results.

Resources