我应该如何验证对 Active Record 对象的访问?
这似乎是一项简单的任务,但我很难找出“轨道”的方法来完成它。
我正在使用 Authlogic 来验证用户,每个用户都有_many:博客、:图片等。我不知道该怎么做是将用户 A 的博客的访问(显示/更新/编辑/删除)限制为用户 A 。
看来我有三个选择
- 将条件 (user_id == current_user.id) 添加到我的所有 Find 语句中
- 使用 before_filter 完成上述
- 操作 使用 default_scope 附加此身份验证条件(但我认为当我去编写测试时这会很痛苦)。
其他人认为解决这个问题的最佳方法是什么?
作为一个附加问题,假设用户 has_many :blogs、博客 has_many :sections 和部分 has_many :images 的情况。在这种情况下,属于博客的所有元素都需要限制为用户 A,但只有博客具有 user_id 列。将相同的身份验证条件附加到部分和图像的最有效/优雅的方法是什么?
谢谢, 麦克风
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.
- Add the condition (user_id == current_user.id) to all of my Find statements
- Use a before_filter to accomplish the above
- 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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
另一种选择是使用
cancan
gem。 https://github.com/ryanb/cancan这真的很简单,你也可以解决你的奖金问题。
例如:
如果您有,则此设置很好。
有关如何设置其余部分,请参阅 Wiki 。
哦,我忘了还有一个关于 cancan 的截屏视频
Another option could be to use the
cancan
gem. https://github.com/ryanb/cancanIt's really straightforward and you can solve your bonus problem as well.
For example:
This setup is good if you have
For how to set up the rest please see the Wiki.
Oh, and I forgot there is also a screencast about cancan
将 before_filter 与检查用户是否经过身份验证的函数一起使用。
Use before_filter with function which checks whether user is authenticated or not.