开发者

How do I add a user model to my application so data is "user" specific in my Rails app

开发者 https://www.devze.com 2023-01-20 09:23 出处:网络
looking to see if there are some ideas on how I should introduce the idea of a logged-in \"user\" that effectively \'federates\' the data....let me explain.

looking to see if there are some ideas on how I should introduce the idea of a logged-in "user" that effectively 'federates' the data....let me explain.

I have been building my app so far as if there is only one user. Me. All the data and reports are specific to me. I just added authlogic.

I now want to be able to introduce a way for a new user to log in, not see any of my data, and use the application. And eventually to pay to us开发者_JS百科e the system.

So far, my assumption is I'd have to go into the models and add a user_id to pretty much each of them, and then go to all controllers and have them search by user.

But I am wondering if there are gems, suggestions, ideas of a better way to federate the data for each user.

Oh...I may want to enable more than one user to have access to some or all of the data belonging to another user. This is for small teams of sales people that may want to share.

So...ideas before I try fumbling around myself...thank you :)


You've got the right idea. You have to make relationships between users and the data models. In some cases, it might be a simple belongs_to :user, but if you want multiple users to access certain data, it's going to have to be a many-to-many relationship has_and_belongs_to_many :users.

Then, we simply change the way we fetch data:

# Some controller, no restrictions
def index
  @reports = Report.all
end

def view
  @report = Report.find(params[:id])
end

# Some controller, with restrictuons
def index
  @reports = current_user.reports.all
end

def view
  @report = current_user.reports.find(params[:id])
end

Using the above logic, users will only see whatever data they have a relationship to.

It's probably going to be a little bit of work if you've already created most of the application, no doubt. What you have to be really, really, really careful with is not leaving any Report.all or Report.find(params[:id]) lying around, as that can lead to vulnerabilities--users would be able to access data that isn't actually theirs.


What you're talking about is called ACL (access control lists). There are a number of plugins for Rails that will do the bulk of the work for you. Google around and see if you can find one that fits your needs.

Edit: After taking a quick look, Acl9 seems to be the most popular Rails 3 compatible one.

0

精彩评论

暂无评论...
验证码 换一张
取 消