What is the difference between ModelName.all and ModelName.where('')
I have the following relations:
User --has many--> Reminders --has many--> Payments
I get all the payments of a user as
payments = User.reminders.collect{|reminder| reminder.payments.between(from_date, to_date)}.flatten
and then
data = payments.select("SUM(amount) as total_payment, MONTH(payment_date) as month, YEAR(payment_date) as year").group("MONTH(payment_date), YEAR(payment_date)").map{|payment| [payment.total_payment, "#{payment.month}/#{payment.year}"]}
I was trying to run the above select and group by query on a dataset which failed with the following exception:
ArgumentError: wrong number of arguments (1 for 0)
from (irb):162:in `select'
The above query runs fine on Payments.where('') but fails on Payments.all or the dataset which I have obtained above.
On debugging I found that Payments.where('') is an ActiveRecord::Relation
object whereas Payment.all is an Array.
An explanation would help me understand the concept and which way should I take. I don't want to run that group by query for each reminder.payments indiv开发者_StackOverflow中文版idually and then sum it up.
You've got an array of Payment objects at that point, rather than a Relation, which represents a query that hasn't been run yet. There's two ways to approach this problem. The first would be to build payments as a relation rather than an array. I would do this by adding a has_many :through
relationship between Users and Payments.
class User < ActiveRecord::Base
has_many :reminders
has_many :payments, :through => :reminders
end
payments = user.payments.between(from_date, to_date)
data = payments.select....
The other way to do it would be to just pass the ids from your array to a where clause:
payments = user.reminders.collect {...}.flatten
data = Payment.where('id in (?)', payments).select...
精彩评论