# Add a condition to every find call of a model

**URL:** <https://www.ruby-forum.com/t/add-a-condition-to-every-find-call-of-a-model/133021>\
**Category:** Rails\
**Created:** [March 26, 2008, 8:05pm UTC](https://www.ruby-forum.com/t/add-a-condition-to-every-find-call-of-a-model/133021 "2008-03-26T20:05:37Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![S\_simon\_S](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/s/b487fb/32.png) [@S\_simon\_S](https://www.ruby-forum.com/u/S_simon_S)\
**Post date:** [March 26, 2008, 8:05pm UTC](https://www.ruby-forum.com/t/add-a-condition-to-every-find-call-of-a-model/133021/1 "2008-03-26T20:05:37Z")

</div>

Hi all!  
I have some models that need a where condition for every select I do.  
Say I have this table:

create\_table “posts”, :force =\> true do |t|  
t.string “title”, :default =\> “”, :null =\> false  
t.text “text”, :default =\> “”, :null =\> false  
t.datetime “created\_at”  
t.integer “user\_id”, :default =\> 1, :null =\> false  
end

So I want every user to see only his posts. Always.  
If I do Post.find() I want to add :conditions =\> [‘user\_id = ?’,  
session[:user\_id]] for every call to find. I call find in a lot of  
actions, like find(params[:id]) or find\_by\_title(‘hello’) and other  
variants of find.  
So my questions: can i add my condition to every call to find by adding  
it only one time somewhere?

Thanks!

---

<div class="post-metadata">

**Author:** ![S\_simon\_S](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/s/b487fb/32.png) [@S\_simon\_S](https://www.ruby-forum.com/u/S_simon_S)\
**Post date:** [March 27, 2008, 9:12am UTC](https://www.ruby-forum.com/t/add-a-condition-to-every-find-call-of-a-model/133021/2 "2008-03-27T09:12:33Z")

</div>

S2 Akira wrote:

> So I want every user to see only his posts. Always.  
> If I do Post.find() I want to add :conditions =\> [‘user\_id = ?’,  
> session[:user\_id]] for every call to find. I call find in a lot of  
> actions, like find(params[:id]) or find\_by\_title(‘hello’) and other  
> variants of find.  
> So my questions: can i add my condition to every call to find by adding  
> it only one time somewhere?

You can scope your find on your user. I assume that you are extracting  
your user, probably with something like:

@current\_user = User.find session[:user\_id]

If so, then replace all your Post finds which restrict to the user with  
a find on @current\_user.posts, such as:

@user\_posts = @current\_user.posts

All #find calls on the Post class can be applied to the  
@current\_user.posts association proxy, so to get the last 5 posts for  
this user:

@last\_5\_posts = @current\_user.posts.find :order =\> ‘created\_at’, :limit  
5
