unable to determine row count Ruby-On-Rails - ruby-on-rails

im trying to build a cart in ruby on rails it requires me to show the output like this : You have 3 items in your cart (3 being the number of items in my cart) and im trying to find the number of rows in the table line_items where the cart_id is 5.
#line_items.find(:all, :condition => { :cart_id => "5"}).count
if anyone know how i should write this, please let me know.. Thanks in advance

You can do it the slow way:
YourModelClass.find(:all, :conditions => { :card_id => 5 }).count
or the fast way:
YourModelClass.count(:conditions => { :card_id => 5 })
The fast way simply does a COUNT(*) inside the database, the slow way pulls the whole result set out of the database, turns it into objects, and then counts them.
There's also the modern Rails3+ way:
YourModelClass.where(:card_id => 5).count
That does a select count(*) from t where card_id = 5 inside the database. Don't use this one though:
YourModelClass.count(:card_id => 5)
That will do a select count(card_id = 5) from t and that's nothing at all like what you want.

it should be something alone the line of
LineItem.count(:conditions => {:cart_id => 5})
since i don't really know what's the model name, and the association... hope this helps =)

Related

Rails :order by date in Postgres returning incorrect order

I have a model called Story that I'm trying to order by the created_at date. Since I've hosted my app on Heroku, which uses Postgresql, I have the following in my controller:
#stories = Story.find( :all, :order => "DATE(created_at) DESC" , :limit => 11)
I would expect this to give the first 11 of my stories, ordered by the creation date, with the newest story first.
Unfortunately, this doesn't work. Most of the stories return ordered correctly, but the first two are flipped. That is, the latest story appears second in the list.
Why would this be? I have a sneaky suspicion that my results aren't ordered at all or are being ordered on the wrong column (maybe id?) and that until now it just happened to be ordered like I expected when displayed on my index page. How can I get it to order as I expect it to?
In case anyone cares, the index view is simply displaying the stories, in order. That is (HAML):
- #stories.each do |story|
= render :partial => "event", :locals => { :event => story }
EDIT
I am suspicious that the created_at is a datetime column and the DATE(...) function disregards the time portion. So it returns the elements created on the same date in a random order. Since the first two stories were created on the same day, but several hours apart, which would explain why they seem to be 'reversed'. If this is the case, what would be the correct syntax to order by both date and time?
I believe you want:
#stories = Story.find(:all, :order => "created_at DESC" , :limit => 11)
Update for Rails 3+:
#stories = Story.order(created_at: :desc).limit(11)
If you are using Rails 3, I would also encourage you to use the cool new query syntax which would be:
#stories = Story.order('created_at DESC').limit(11)
See Active Record Query Interface for more information.

Rails 3 select random follower query efficiency

I have a method that selects 5 random users who are following a certain user, and adds them to an array.
Relationship.find_all_by_followee_id( user.id ).shuffle[0,4].each do |follower|
follower = User.find(follower.user_id)
array.push follower
end
return array
I'm wondering, is this an efficient way of accomplishing this? My main concern is with the find_all_by_followee_id call. This returns a list of all the relationships where the specified user is being followed (this could be in the 100,000s). And then I shuffle that entire list, and then I trim it to the first 5. Is there a more efficient way to do this?
You can try this:
Relationship.find_all_by_followee_id( user.id, :order => 'rand()', :limit => 5 ) do |follower|
follower = User.find(follower.user_id)
array.push follower
end
return array
Btw, this will work with MySql. If you are using PostgreSQL or anything else you may need to change the rand() with any valid random function that your DB supports.
Some minor changes to make it a little more clean:
return Relationship.find_all_by_followee_id( user.id, :order => 'rand()', :limit => 5 ).collect {|follower| User.find(follower.user_id) }
You can also use a join in there in order to prevent the 5 selects but it won't make much difference.
Edit1:
As #mike.surowiec mentioned.
"Just for everyones benefit, translating this to the non-deprecated active record query syntax looks like this:"
Relationship.where(:followee_id => user.id).order( "random()" ).limit( 5 ).collect {|follower| User.find(follower.user_id) }

Find first two records from collection

I want to retrieve the first two records from collection such that, collection is like:
#collect_firstnames = #name.firstnames
From this collection I want to fetch first two records...
I used limit it is not working, :limit => 2
I take it that #name.firstnames is a has_many relationship. You need to pass the options to all:
#name.firstnames.all(:limit => 2)
You can use the :limit option like this:
#first_two = Name.find(:all, :limit => 2)
Edit
It's the same idea, assuming firstnames is a relationship (just like Swanand said below)
#first_two = #name.firstnames.all(:limit => 2)

Getting the id with a rails find with :select

I have this rails find that i need to get the id as well but if i put the id in the :select wont it effect the query and is there another way to get the id
#past_requests = Request.find_all_by_artist(name, :conditions => ["showdate < ?", Time.now], :select => "distinct venue, showdate")
#past_requests = Request.find_all_by_artist(name, :group => "venue, showdate")
code long for view. i'm remove your condition. sorry about this. Hope it'll helpful for you. :)
To be fair in cases where distinct returns a single row out of maybe 5 duplicates who's to say which id out of those 5 should be displayed in your result? I'm afraid what you are asking for is not practical. Maybe you misunderstand what distinct is used for ? Give us more info pls.

Rails, Get a random record when using :group

How do I get a random record when using :group?
#paintings = Painting.all(:group => "user_id", :order => "created_at DESC")
This gives me the latest painting for each user. Now I would like to select a random painting from each user instead of the latest. The order of the paintings should still be the same, so that the user that have been the most active will get his/her random painting displayed first.
painting150 (user1)
painting200 (user2)
painting231 (user3)
Is this possible?
Best regards.
Asbjørn Morell.
This answer is specific to Rails, but since you are using ActiveRecord, I am assuming it should be fine.
unique_paintings = []
#paintings.group_by(&:user_id).each do |user_id, paintings|
unique_paintings << paintings[rand(paintings.size-1)]
end
unique_paintings.sort_by(&:created_at)
The group_by most certainly messes up the created_at sort you did in the query, so I did a sort_by as the last step. You might want to get rid of it in the query since you'll have to do it anyway here.
#painting = #paintings[rand(#paintings.size-1)]
(or paintings.count, dont know the right method yet)
Assuming you have MySQL, you can try:
#paintings = Painting.all(:group => "user_id", :order => "RAND()")
you could do something like this but it will suffer as your number of records grow
#paintings = Painting.find(:all, :order => 'RAND()').map{ |i| i.user_id }.uniq

Resources