Hi,
its the first time I post here. I have a problem that i can somehow not solve. Just for the record, I know what instance and class methods are (even if I may not understand them completely ;-) Here is my model code:
class Car < ActiveRecord::Base
has_many :drives
has_many :users, :through => :drives
def self.user_ids()
ids = []
self.users.each do |user|
ids += user.id
end
ids
end
def self.common_times()
start_times = []
stop_times = []
self.drives.each do |drive|
drive.start_date_time += start_times
drive.stop_date_time += stop_times
end
times = { :start => start_times.sort.last, :stop => stop_times.sort.first}
end
what I want is an array of all users using the car (which I use to check if a given user is already connected to the car for permissions etc.. Is there a better way to check if two datasets are already connected without doing SQL queries all the time?) and which start and stop times they prefer. I need than a hash with the latest starting time and the earliest stop time. Somehow the user_ids method works (even if I think it should be an instance method) and the common_times is always missing. if I define them both as an instance method I have problems with fixnum and array stuff (like "+").
user_id:
"TypeError: can't convert Fixnum into Array"
common_times:
"NoMethodError: You have a nil object when you didn't expect it!
You might have expected an instance of Array.
The error occurred while evaluating nil.+"
I guess the best way is to make them instance methods. But then I need to refer differently to the other models as users and drives.
Why does user_ids work as an instance method even if declared as a class method?
How do I call already loaded models [c=Car.find(:all, :include => :drives)] inside an instance method?
Funny thing was also, that as long as they were class methods I could delete them and restart mongrel and they would still work (user_ids) and not work (common_times).
I am pretty confused right now and hop you can help me. And sorry for my bad english (I am german :-)