Pat_Maddox
(Pat Maddox)
February 10, 2007, 7:33pm
1
I usually do write a simple access? method on my User model. For example:
class User
def access?(article)
id == article.user_id
end
end
Then in your controller you do use a before_filter
class ArticlesController < ApplicationController
before_filter :check_article_access
def show
end
protected
def check_article_access
@article = Article.find params[:id]
unless current_user.access? @article
redirect_to user_url(current_user)
return false
end
end
end
There's still only one query, you just create the @article instance
variable in a different method.
hth
Pat
Rick_Olson
(Rick Olson)
February 10, 2007, 7:39pm
2
I usually do write a simple access? method on my User model. For example:
class User
def access?(article)
id == article.user_id
end
end
I usually do the opposite.
class Article
def accessible_by?(user)
user && user_id == user.id
end
end
Pat_Maddox
(Pat Maddox)
February 10, 2007, 7:54pm
3
Is that a better way, or is it just preference?
I throw the method on user because it lets me build out a permission
system as needed. I start with checking ids, and then maybe it
becomes
def access?(article)
role == "root" || article.user_id == id
end
and then eventually we might end up using a full-fledged permission system.
Pat
JR1
(JR)
February 11, 2007, 2:21am
4
If user has many articles and article belongs to user, ActiveRecord
affords you the option of referencing articles within the user's scope
like this:
@article = @user.articles.find (article_id)
or:
@article = @user.articles.create (:params[:article])
Jeff1
(Jeff)
February 11, 2007, 5:16am
5
Actually, no. As long as all of those objects respond to the user_id
message, you're golden - perhaps if I rename the argument that Pat
used it will be clearer:
def access?(model)
id == model.user_id
end
So for every model the belongs_to :user, you can ask the user object
if it can access this model. If you want to be extra safe:
def access?(model)
false unless model.responds_to? 'user_id'
id == model.user_id
end
This is where Ruby really shines above the statically-typed languages
I used to use a long time ago in a galaxy far, far way.
Jeff
softiesonrails.com