I'm not sure why you want to do this at all. The best approach is to use the controller to scope your models. This type of thing doesn't belong to the model.
def index
@albums = current_user.albums
end
If you want to avoid the repetition, create methods to retrieve the object. So instead of this:
def show
@album = current_user.albums.find(params[:id])
end
def edit
@album = current_user.albums.find(params[:id])
end
# etc...
You can do this:
def index
albums
end
def show
album
end
def update
if album.update(album_params)
end
# etc...
private
def albums
@albums ||= current_user.albums
end
def album
@album ||= current_user.albums.find(params[:id)
end
You can even avoid calling the album method from the action by using a before_filter
, but this is not a good way. You always tend to forget to add and remove actions from the filter.
before_action :set_album, only: [:show, :edit, :update, :destroy]
def set_album
@album ||= current_user.albums.find(params[:id])
end
Then your instance variables are created in one place. As @wacaw suggested, if this appeals to you, you can take it further and use the decent_exposure gem. Personally, I am happy to stop at the controller and use instance methods in my views.
If you have more complex authorisation needs I suggest you use pundit or cancan, although the latter does not appear to be actively maintained.
There is more on decent_exposure on Rails Casts. If you really fancy this type of scoping, look at this Rails Cast on Multitenancy with Scopes. But that is meant for organisations that have many of users, not a single user.