[Rails] Active Record problem
by Nadav Blum other posts by this author
Aug 29 2005 6:41AM messages near this date
[Rails] SF Bay Area: Ruby/Rails BBQ next weekend (Menlo Park)
|
Re: [Rails] Active Record problem
Hi all
I am new to Rails, and obviously I'm missing something, I'll get straight to the question:
A User has many operations (granted to her), each Operation is associated with an OperationT
ype. Each Operation may be associated with more then one User.
So the model goes like this:
class User < ActiveRecord::Base
has_and_belongs_to_many :operations
end
class Operation <ActiveRecord::Base
belongs_to :operation_type,
has_and_belongs_to_many :users
end
class OperationType <ActiveRecord::Base
has_many :operations
end
And I have users, operations, operations_users (join table) & operation_types tables as need
ed.
Now for a given user, I want to fetch all the types of the operations associated with her (O
perationType classes).
So there is one very inefficient way that goes like this:
(suppose user_id holds the user id)
user = User.find(user_id)
user_operations = user.operations
@user_operation_types = Array.new
for op in user_operations
operation_type = op.operation_type
if !@user_operation_types.include? operation_type
@user_operation_types << operation_type
end
end
And I get all the operation types associated with the user's operations in the @user_operati
on_types array. But this is inefficient (many selects) and doesn't seem good.
I tried to change the first line to: user = User.find(user_id, :include=> :operations)
but then I get only one entry in the @user_operation_types array, which is incorrect (there
should be more).
What is the right way to do this?
Thanks for your help
Nadav
__________________________________________________
Do You Yahoo!?
Tired of spam? Yahoo! Mail has the best spam protection around
http://mail.yahoo.com
Attachments:
unknown1
unknown2
unknown3
unknown4
Thread:
Nadav Blum
Andrew Stone
|