First off, I want to apologize if this topic has been previously
addressed on the list. I looked, but could have missed it.
I’m trying to run a subscription site, and have created a Subscription
resource. I now have a table that holds a user_id, sub_user_id, and
expiration (in UTC.) I’ve constructed a query (that doesn’t blow up!)
in my application controller that should check if a user’s
subscription is valid:
def check_subscription(current_user_id, content_owner_id)
@subscription = Subscription.find(:all,
:conditions => { :user_id =>
current_user_id,
:sub_user_id =>
content_owner_id,
"((expiration
?))" => Time.now.utc })
if @subscription.nil?
redirect_to root_url
end
end
I would like to use this as a before filter in my other controllers,
so I can keep the code DRY. However, I’m at a loss when it comes to
passing in the current_user_id and content_owner_id into this method
through a before_filter. (For instance, every post can be marked as
“subscription” required, and if the user has an active subscription,
let them see the post.)
I hope all of this makes sense.
Thanks!
-Nicholas
Nicholas Y. wrote:
I would like to use this as a before filter in my other controllers,
so I can keep the code DRY. However, I’m at a loss when it comes to
passing in the current_user_id and content_owner_id into this method
through a before_filter. (For instance, every post can be marked as
“subscription” required, and if the user has an active subscription,
let them see the post.)
I think, in this case, I would add a name_scope to User model that finds
the user’s active/valid subscriptions:
current_user.valid_subscriptions(content_owner)
Use a before_filter to load the content_owner in your controller(s).
I’ll leave it as an exercise for you to figure out how to write the
named_scope to do that.
Try removing current_user_id and current_owner_id from the parameters
list and moving them into ApplicationController as methods (like you
would see with Authlogic/restful-authentication).
class ApplicationController
before_filter :check_subscriptions
def current_user_id
# however you collect this
# or nil if it can’t be set
end
def current_owner_id
# however you collect this
# or nil if it can’t be set
end
def check_subscriptions
redirect_to root_url unless current_user_id && current_owner_id
# the rest of your method as defined above
end
end
Also, you may want to look into using a third-party library for this.
I use be9’s ACL9 authorization plugin to achieve something very
similar in one of my apps.
Best,
Jeff Tucker
On Nov 10, 1:25 pm, Nicholas Y. [email protected]
On Nov 10, 1:25 pm, Nicholas Y. [email protected]
wrote:
@subscription = Subscription.find(:all,
:conditions => { :user_id =>
current_user_id,
:sub_user_id =>
content_owner_id,
“((expiration> ?))” => Time.now.utc })
Somewhat offtopic, but how is the bit with a placeholder working? I
just tried it against 2.3 and got an error about 'wrong number of bind
variables".
–Matt J.