Applying conditions to ActiveRecord call in model.rb

If @c is an instance for the User class and lets say I want to call
@c.pictures, which would be the user’s pictures.

How can I setup up RoR so that I could append the condition
“status=‘available’” to the conditions arguments EVERYTIME .pictures is
called. This way I can only call available pictures

Is there some kind of filter I can apply to the picture.rb or my
user.rb?

Eric G. wrote:

If @c is an instance for the User class and lets say I want to call
@c.pictures, which would be the user’s pictures.

How can I setup up RoR so that I could append the condition
“status=‘available’” to the conditions arguments EVERYTIME .pictures is
called. This way I can only call available pictures

class User
has_many :pictures, :conditions => [‘status = ?’, ‘available’]
end

Not sure if the SQL is called again and again or if the values are
cached after the first call. Let me know.

Cheers
Nic

Dr Nic,

I dont really know how to tell if they are cached or not, but your
advice solved my problem. Thanks a lot.

Eric

Dr Nic wrote:

Eric G. wrote:

If @c is an instance for the User class and lets say I want to call
@c.pictures, which would be the user’s pictures.

How can I setup up RoR so that I could append the condition
“status=‘available’” to the conditions arguments EVERYTIME .pictures is
called. This way I can only call available pictures

class User
has_many :pictures, :conditions => [‘status = ?’, ‘available’]
end

Not sure if the SQL is called again and again or if the values are
cached after the first call. Let me know.

Cheers
Nic

Eric G. wrote:

I dont really know how to tell if they are cached or not, but your
advice solved my problem. Thanks a lot.

You can tell if its cached by watching the log. Assuming you are
running in development, open a shell window, cd to your project
directory, and type “tail -f log/development.log”. Whenever you do a
query you’ll see the SQL logged to that file. If an association is
returning cached results, you won’t see a new query in the log. If you
need to force a query you can either do user.pictures(true) or
user.pictures.reload. Usually caching is a good thing.


Josh S.
http://blog.hasmanythrough.com

class User < ActiveRecord::Base
has_many :pictures, :conditions => ‘status = “available”’
end

-Jonathan.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs