Rails Active Record Find(:All, :Order => ) Issue

Rails Active Record find(:all, :order = ) issue

I notice that in your first example, the simple :order => "date", record 7 is sorted before record 1. This order is also how you see the results in the multi-column sort, regardless of whether you sort by attending.

This would seem to make sense to me if the dates weren't exactly the same, and the date for 7 is before the date for 1. Instead of finding that the dates are exactly equal then proceeding to sort by attending, the query finds that the dates are not equal and simply sorts by that like all the other records.

I see from browsing around that SQLite doesn't have a native understanding of DATE or DATETIME data types and instead gives users the choice of floating point numbers or text that they must parse themselves. Is it possible that the literal representation of the dates in the database are not exactly equal? Most people seem to need to use date functions so that dates behave like you would expect. Perhaps there's a way to wrap your order by column with a date function that will give you something concrete to compare, like date(date) ASC, attending DESC. I'm not sure that syntax works, but it's an area to look at for solving your problem. Hope that helps.

Find model records by ID in the order the array of IDs were given

Note on this code:

ids.each do |i|
person = people.where('id = ?', i)

There are two issues with it:

First, the #each method returns the array it iterated on, so you'd just get the ids back. What you want is a collect

Second, the where will return an Arel::Relation object, which in the end will evaluate as an array. So you'd end up with an array of arrays. You could fix two ways.

The first way would be by flattening:

ids.collect {|i| Person.where('id => ?', i) }.flatten

Even better version:

ids.collect {|i| Person.where(:id => i) }.flatten

A second way would by to simply do a find:

ids.collect {|i| Person.find(i) }

That's nice and simple

You'll find, however, that these all do a query for each iteration, so not very efficient.

I like Sergio's solution, but here's another I would have suggested:

people_by_id = Person.find(ids).index_by(&:id) # Gives you a hash indexed by ID
ids.collect {|id| people_by_id[id] }

I swear that I remember that ActiveRecord used to do this ID ordering for us. Maybe it went away with Arel ;)

Trying to order the results of includes in activerecord

As Abishek Kumar mentioned in his answer, you should probably use joins instead of includes, since includes is only there to prevent the N+1 query problem. It does seem to allow you to sort by association as well, but it will not help you if your associations have custom names.

I think you will have to step a little bit outside of ActiveRecord's nice and cozy place for a while, and write the join statement manually:

Claim.all
.joins("INNER JOIN users AS treated_bys ON claims.treated_by_id = treated_bys.id")
.order("treated_bys.last_name ASC")

...then you can spinkle the query with includes statements as well, if you need that to avoid N+1 queries, etc.

Rails find all order, found 0 results expected 2

Thanks to ahmed and snehal, I was able to find out the answer I'm looking for, which is

Topic.left_outer_joins(:votes).group('topics.id').order('count(topics.id) DESC')

ActiveRecord.find(array_of_ids), preserving order

The answer is for mysql only

There is a function in mysql called FIELD()

Here is how you could use it in .find():

>> ids = [100, 1, 6]
=> [100, 1, 6]

>> WordDocument.find(ids).collect(&:id)
=> [1, 6, 100]

>> WordDocument.find(ids, :order => "field(id, #{ids.join(',')})")
=> [100, 1, 6]

For new Version
>> WordDocument.where(id: ids).order("field(id, #{ids.join ','})")

Update:
This will be removed in Rails 6.1 Rails source code

How to get last N records with activerecord?

Updated Answer (2020)

You can get last N records simply by using last method:

Record.last(N)

Example:

User.last(5)

Returns 5 users in descending order by their id.

Deprecated (Old Answer)

An active record query like this I think would get you what you want ('Something' is the model name):

Something.find(:all, :order => "id desc", :limit => 5).reverse

edit: As noted in the comments, another way:

result = Something.find(:all, :order => "id desc", :limit => 5)

while !result.empty?
puts result.pop
end

Rails: Find all with conditions

Try this.

@fromcanada = User.find(:all, :conditions => { :country => 'canada' })

edit:
As jason328 pointed out, the above answer is deprecated in 3.2, and an updated answer would be

@fromcanada = User.where(:country => 'canada')

active record query order where first

try this:

restaurants = Restaurant.where('last_visit < ?', Date.yesterday).order({ rating: :asc })

this gives you a collection of restaurants matching your constraints passed in where method, the result of which is chained to order method that orders the collection in ascending order of the values in rating column of restaurants table. use :desc if you want to order in descending order.

Then, you can retrive last object with

restaurant1 = restaurants.last

Problems with Active Record Rails 4

Alright, figured it out.

I was using @order.save which was not processing the error message!!!!!!!!
After @order.save! it gave me the validation error in another model.
I commented that out and it worked.

I iterated current.cart_items and assigned the cart_id to nil and order_id to @order.id essentially clearing the cart and "transferring" the items over.

I couldn't figure out a way using destroy_all though. I think this is impossible like @Sri said.

Thanks alot!

So the end code was this:

@order = Order.create!(users_id: current_cart.users_id)

current_cart.cart_items.each do |item|
item.order_id = @order.id
item.save!
end

if @order.save
current_cart.cart_items.each do |item|
item.cart_id = nil
item.save!
end


Related Topics



Leave a reply



Submit