I'm having problems with getting a value from a single column call.
select sum(price) as testPrice from sales where quantity > 10
but when I inspect the resultset, I get the following,
[#"5"}>]
Any help is appreciated, thank you.
That is a very strange result. I am curious why you are not writing the query using ActiveRecord methods:
#testPrice = Sale.sum(:price, :conditions => "quantity > 10")
Related
I'm having trouble sorting my table based on the votes column, votes is a multivalued attribute so I use count and try to sort it based on that. here is the code
#topics = Topic.find(:all,:order=>'#topic.votes.count DESC')
Rails returns an error that says
ActiveRecord::RecordNotFound in TopicsController#index
Couldn't find all Topics with 'id': (all, {:order=>"#topic.votes.count DESC"}) (found 0 results, but was looking for 2)
Just starting out with rails and still confused with some things, your help will be much appreciated.
this is Rails 2 syntax being used in higher Rails version.
You can do something like this:
Topic.joins(:votes).group('topics.id').order('count(topics.id) DESC')
Instead of join include is best and faster option
Topic.include(:votes).group('topics.id').order('count(topics.id) DESC')
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')
I am using c9 cloud ruby on rails and my Rails version is 5.0.0.1
I want to compose an ActiveRecord query to select the restaurant with the best rating which has not been visited yesterday. When I applied all where, order and first in the query, it throws an error. However, if I don't use where or order, it works fine.
This works:
restaurant1= Restaurant.order('rating').last!
#suggested_restaurants=restaurant1.name
This gives strange results:
restaurant1=Restaurant.order('rating').where{last_visit<Date.yesterday}
#suggested_restaurants=restaurant1
Results: #<ActiveRecord::QueryMethods::WhereChain:0x000000046af7f8>
This triggered error:
restaurant1=Restaurant.order('rating').where{last_visit<Date.yesterday}.last
#suggested_restaurants=restaurant1
Error: undefined method 'last' for #ActiveRecord::QueryMethods::WhereChain:0x00000004587a10>
I can get around this issue by using find_by_sql but I'd like to know why and how to use where in Rails 5. Thanks a lot!
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
This will give you the Relation for restaurants that have not been visited today, then you can call .last on that.
restaurant1 = Restaurant.order('rating').where('last_visit<?', Date.yesterday).last
#suggested_restaurants=restaurant1
i was trying to sort values of a table with sort_link from Ransack. i found an example which is really helpful. but, i think i'm having problem with 'distinct'. i got this error 'ORDER-BY expressions must appear in SELECT list; DISTINCT'.
my code looks like this :
q =user.joins(:buyer).order('users.name')
ransack = params["filter"]
#search = q.search(ransack)
#users = #search.result(:distinct=>true)
do i forget something? thanks in advance!
As per this issue you might be able to solve this with an ActiveRecord joins query or select query to add the columns needed, for example:
q = user.order('users.name')
ransack = params["filter"]
#search = q.search(ransack).
result(:distinct=>true).
joins(:buyer).
includes(:buyer)
#users = #search.all
You have distinct as true. Ransack called the distinct value in the wrong manner with Postgresql, thefore you getting this error. If you use another database, you mostlikely would not.
So, if you make distinct false, you will not get this error. If you want to know why you need distinct, check out:
http://www.w3schools.com/sql/sql_distinct.asp
I am trying to find a way to include distinct if I need it. when I find out, I will edit this answer.
I have about 500 outlets. Each outlet will be monitored a minimum of one time per day. I am trying to get a list of outlets that have been monitored each day.
I am having a problem with the query at the moment, any help is appreciated:
<% for outlet in #outlets %>
<% if Monitoring.exists?( :outlet_id => outlet.id, 'DATE(created_at) = ?', Date.today ) %>
The #outlets is an instance variable containing Outlet.all.
This query leaves me with a syntax error. What would be the correct way to do this? I'm trying to check that the Monitoring belongs to the Outlet, and that the Monitoring record was created today.
Also, I'm not entirely sure of the speed implications of this query. There will be a max of 2000 outlets on a page at one time (it's a dashboard, so they appear as either red or green dots).
Any help greatly appreciated.
You're getting a syntax error because you're trying to mix implicit-Hash and implicit-Array arguments:
Monitoring.exists?(:outlet_id => outlet.id, 'DATE(created_at) = ?', Date.today)
The exists? methods wants a Hash as its single argument. You want to use an SQL function in the query though, that means that you have to use the Model.where(...).exists? form:
Monitoring.where(:outlet_id => outlet.id).where('date(created_at) = ?', Date.today).exists?
That still leaves you hitting the database over and over again to light up your lights. You could precompute the whole mess with something like this:
counts = Monitoring.where('date(created_at) = ?', Date.today).count(:group => :outlet_id)
And then look use counts.has_key? outlet.id in your loop. Adding a where(:outlet_id => outlet_ids) (where outlet_ids are the IDs you're interested in) might make sense as well. You might be able to combine the count query with the query that is generating the #outlets too.
I'm trying to do the following in rails 3:
#groups_active = Group.active_groups(current_user)
active_groups is a scope. This query works fine. I then want to do the following:
if #groups_active.count > 9
#groups_active[0..10]
end
Meaning if there are more than 10 items in the #groups_active, take just the TOP 10, which thanks to the scope ordering are the most active.
Suggestions? Thanks
I'm not sure what your problem is. You can limit the number of results from a query with Model.your_scope.limit(10), and if it is a query that doesn't work with a SQL LIMIT then you can use Model.your_scope.first(10). That's an Array#first, which accepts a fixnum argument to be used as expected…
#groups_active = Group.active_groups(current_user).limit(10)
or you could add the .limit(10) part to your scope.
Edited
I would go with one limit(10) request and one count. It could be more effective then retrieving 20, 50, or more records and using only the first 10 of them.
But still, it requires testing and benchmarking.