Add a condition to every find call of a model

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!

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

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