1
votes

This seems like a straightforward task, but I'm having trouble figuring out the "rails" way to do it.

I'm using Authlogic to authenticate Users, and each user has_many :blogs, :pictures, etc. What I'm not sure how to do is restrict access (show/update/edit/delete) of User A's blog just to User A.

It seems I have three options.

  1. Add the condition (user_id == current_user.id) to all of my Find statements
  2. Use a before_filter to accomplish the above
  3. Use the default_scope to append this authentication condition (But I think this will be a pain when I go to write tests).

What have others found to be the best approach to this problem?

As a bonus question, suppose it's the case that a User has_many :blogs, a Blog has_many :sections, and a Section has_many :images. In this case, all of the elements belonging to a blog need to be restricted to User A, but only the blog has the user_id column. What's the most efficient/elegant way of appending the same authentication condition to the Sections and Images?

Thanks, Mike

2

2 Answers

1
votes

Another option could be to use the cancan gem. https://github.com/ryanb/cancan

It's really straightforward and you can solve your bonus problem as well.

For example:

can :manage, Blog, :user_id=>user.id
can :manage, Section, :blog=>{:user_id=>user.id}
can :manage, Image, :section=>{:blog=>{:user_id=>user.id}}

This setup is good if you have

Blog belongs_to User
Section belongs_to Blog
Image belongs_to Section

For how to set up the rest please see the Wiki.

Oh, and I forgot there is also a screencast about cancan

0
votes

Use before_filter with function which checks whether user is authenticated or not.