Forum: Ruby on Rails Better to pass Activerecord objects or ids as parameters?

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Jay B. (Guest)
on 2009-02-26 20:40
Hi all,

I'm wondering what the best practices/conventions are for passing
parameters to models I am writing. Is it better to pass ActiveRecord
objects, or their database IDs?

In my current application, I've been passing mostly ActiveRecord
objects, because I'm generally using some attributes of that object.
Passing the ID and then doing a find all over again seems like a waste.

On the other hand, I'm finding that most of the code that I'm pushing
out of the controllers into my model is likely to have IDs, since users
are often submitting forms with the object IDs. In those cases, I'm
doing an extra find in the controller to get the object to pass to the
model, which in many cases is simply  doing a DB call using the ID as a
condition.

So, my question is, what is recommended by the experts?

1. Pass only ActiveRecord objects
2. Pass only database IDs
3. Pass whatever is more efficient for the DB in the particular use case
(this seems like a headache for overall application consistency)
Frederick C. (Guest)
on 2009-02-26 21:13
(Received via mailing list)
On Feb 26, 6:40 pm, Jay Bo <removed_email_address@domain.invalid> wrote:
> Hi all,
>
> I'm wondering what the best practices/conventions are for passing
> parameters to models I am writing. Is it better to pass ActiveRecord
> objects, or their database IDs?
>
I personally would pass activerecord objects. Sometimes you might
waste a little if you do just use that object for it's id but I
wouldn't worry about that too much. Apart from anything else doing the
find validates that the id does actually correspond to a real object.
You might consider skipping it for something that's really on the hot
path but I really wouldn't do that from the outset.

Fred
This topic is locked and can not be replied to.