I need to do some filtering on my ActiveRecord models, I want to filter all my model objects by owner_id. The thing I need is basically the default_scope for ActiveRecord.
But I need to filter by a session variable, which is not accessible from the model. I've read some solutions, but none works, basically any of them says that you can use session when declaring default_scope.
This is my declaration for the scope:
class MyModel < ActiveRecord::Base
default_scope { where(:owner_id => session[:user_id]) }
...
end
Simple, right?. But it fails saying that method session does not exists.
Hope you can help
You will not be able to incorporate this into a default_scope. This would break every usage within (e.g.) the console as there is no session.
What you could do: Add a method do your ApplicationController like this
This method will return a scope anyhow.
Session related filtering is a UI task, so it has its place in the controller. (The model classes do not have access to the request cycle, session, cookies, etc).
What you want is
Since filtering by ownership of current user is a typical scenario, maybe you could consider using standard solutions, like search 'cancan gem, accessible_by'
Also be aware of the evils of default_scope. rails3 default_scope, and default column value in migration
Session objects in the Model are considered bad practice, instead you should add a class attribute to the
User
class, which you set in anaround_filter
in yourApplicationController
, based on the current_userand in your
ApplicationController
do:And now in your
MyModel
you can do the following: