如何限制在 Ruby on Rails 中创建帖子的特定用户进行编辑?
我已经使用 ruby 创建了一个消息发布功能,我现在遇到的问题是编辑帖子的功能可用,但无论是谁发布了原始帖子,任何单个用户都可以访问它。我怎样才能使编辑“链接”只能由原始海报查看或访问或使用。如果需要任何代码请询问,谢谢。
这是我现在得到的错误:
undefined local variable or method `current_user' for #<ActionView::Base:0x4cdbb48>
Extracted source (around line #7):
4: <dd>
5: <%= car.name %><br />
6: <%= car.description %><br />
7: <%= link_to('edit', edit_post_path(@car)) if current_user.cars.include?(@car) %>
8: <%= link_to "Delete",
9: :controller => :car,
10: :action => :delete,
I have created a message posting feature using ruby the problem I now have is the function editing the post is available but it is accessible by ever single user no matter who posted the original post. How can I make it so the edit 'link' is only viewable or accessible or usable by the original poster. If any code is required please ask, thanks.
This is the error I get now:
undefined local variable or method `current_user' for #<ActionView::Base:0x4cdbb48>
Extracted source (around line #7):
4: <dd>
5: <%= car.name %><br />
6: <%= car.description %><br />
7: <%= link_to('edit', edit_post_path(@car)) if current_user.cars.include?(@car) %>
8: <%= link_to "Delete",
9: :controller => :car,
10: :action => :delete,
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您有办法获取用户对象,那么您应该与您的帖子建立如下关系:
这可以让您获取并构建以用户为范围的帖子,如下所示:
Enumerable#detect 可以循环遍历数组并返回第一个项目在块中评估为 true,如下所示:
大多数 Rails 应用程序都有某种帮助程序来访问当前登录的用户。如果没有,我建议您在 application_controller 中放置一个,如下所示:
将编辑和更新操作中的查找范围限制为用户拥有的帖子,如下所示:
并在您的视图中:
If you have a way of getting at the user object, you should have relationships to your posts like this:
This lets you get and build posts scoped to the user like so:
Enumerable#detect can loop over an array and return the first item that evalutates to true in a block like so:
Most Rails apps have some kind of helper to access the currently logged-in user. If not I suggest you put one in application_controller like this:
Scope the find in edit and update actions to posts the user owns like this:
and in your view:
您需要将帖子链接到模型中的创建用户,并检查编辑操作中的所有权和/或权限。
最好使用 cancan gem 来处理权限,并查看 这个railscast 使用它来实现与您的需求非常相似的保护。
Railscast 将 cancan 与 authlogic 结合使用,但它也可以与其他身份验证一起使用。
You need to have the post linked to the creating user in your model, and to check ownership and/or permission in the edit action.
It might be good to use the cancan gem for handling the permission, and to look at this railscast on using it to do a very similar protection to your need.
The railscast uses cancan with authlogic, but it can work with other authentication as well.