Rails 3, CanCan to limit all query results throughout the app based on User's InstanceID

百般思念 提交于 2019-12-11 18:36:35

问题


I have two tables Users (name, email, password, instance_id, etc...) example: james bond, james@abc.com, 1 Instance (id, domain) example: 1, abc.com

Through out the application I want to make sure James Bond only sees data that is assigned to his instance = 1

So if I have a books table with (name, desc, instance_id), he only sees his instance's books.

I'm told CanCan is the way to go for this but I don't see how to make something set globally like the above, it seems more role based like admin, moderator, etc... Which I'll need but at a level lower than the data rules mentioned above.

Thoughts?


回答1:


you could try using scopes like:

class Books < ActiveRecord::Base
# .... code ....
scope :personal, proc {|user| where(:instance_id => user.instance_id) }
# .... code ...
end

Now you can do:

@personal_books = Books.personal(@user)

you can read more about scopes here: http://www.railsdispatch.com/posts/rails-3-makes-life-better (scroll down a little bit)

Another way is to make an association like

User has_many Books through Instance

Then you'd have an additional legacy table mapping user to books over their instance. It's an n:m relation. So a book could belong to multiple instances.

It would look like this:

User Table:

Users (name, email, password, instance_id, etc...)

Book Table:

Books (name, desc) # no more instance_id !

Mapping Table:

Assignments (instance_id, book_id)

And your Models would look like:

class Assignment < ActiveRecord::Base
  belongs_to :book      # foreign key - book_id
  belongs_to :instance  # foreign key - instance_id
end

class Instance < ActiveRecord::Base
  has_many :assignments
  has_many :books, :through => :assignments
end

class Books < ActiveRecord::Base
  has_many :assignments
  has_many :users, :through => :assignments
end

class User < ActiveRecord::Base
  belongs_to :instance
end

The code to get all books of an user's instance would look like:

@user       = User.find(:first)
@books      = @user.instance.books.find(:all)

(I recommend you to read http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html )

Edit

You could try this if a book always belongs to only one instance:

class User < ActiveRecord::Base
  belongs_to :instance
end


class Instance < ActiveRecord::Base
  has_many :users
  has_many :books
end


class Books < ActiveRecord::Base
  belongs_to :instance
end

So you grab a user's books like:

@user.instance.books.find(:all)


来源:https://stackoverflow.com/questions/3661275/rails-3-cancan-to-limit-all-query-results-throughout-the-app-based-on-users-in

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!