如何制作,以便用户只能使用Devise编辑/查看属于他们的项目?我似乎无法弄明白。我研究并发现在我的清单控制器索引中设置current_user并创建方法以及将关系放在我的用户模型和清单模型中。我正在创建一个清单,用户可以在其中创建标题和名称,同时在该清单中添加项目,因此我还有一个项目模型。我读过康康,但不太确定这是不是我想要的。我只是希望能够在用户登录创建清单时才能拥有它,列表只属于他们,因此当他们注销时,它不会显示他们创建的任何清单。当他们重新登录时将显示创建的清单。我知道它相当简单,但无法确定任务。谁能帮忙。我在这个项目上使用rails 4。谢谢!
答案 0 :(得分:2)
您可能想要编写如下控制器:
class ChecklistsController < ApplicationController
before_action :set_checklist, only: [:show, :edit, :update, :destroy]
def index
@checklists = current_user.checklists
end
def new
@checklist = current_user.checklists.new
end
def create
@checklist = current_user.checklists.create(checklist_params)
end
def show
end
def edit
end
def update
@checklist.update_attributes(checklist_params)
# ...
end
def destroy
@checklist.destroy
# ...
end
private
def load_checklist
@checklist = current_user.checklists.find(params[:id])
end
def checklist_params
params.require(:checklist) # .permit(...)
end
end
答案 1 :(得分:1)
权限有两个主要方面。身份验证和授权。
Devise提供身份验证,基本上是“这个用户就是这个人”。它通过登录验证。
像cancan这样的库有助于提供授权,即“允许此用户执行此操作”。您可以使用cancan Define an ability with a block执行以下操作:
can :read, Item, Item.all do |item|
item.owner == current_user
end
答案 2 :(得分:1)
:
# user.rb
has_many :items #or somehow like this if you have joins or something else
控制器中的:
before_filter :authenticate_user! #inherit devise helpers and methods in controller
def index
@items = current_user.items #for the current !!signed-in!! user
# other necessary code...
end
def edit
@item = current_user.items.find(params[:id])
# other necessary code... show action would include the same row for @item finding
end
can-can gem真的可以用,如果你有很多授权问题,不仅仅是你提到的......有很多教程,而不是最糟糕的是在cancan文档中
答案 3 :(得分:1)
您必须将user_id外键放在所需的所有模型中 这个限制。
并且编辑和查看操作执行类似这样的操作
示例: -
用户has_many:帖子
并发布belongs_to:user
def edit
@post = current_user.posts.find(params[:id])
end
def update
@post = current_user.posts.find(params[:id])
@post.update_attributes(params[:id])
respond_with @post
end
def show
@post = current_user.posts.find(params[:id])
end
答案 4 :(得分:1)
我知道这是一篇非常古老的帖子,但要回答你的问题,你需要做的就是将过滤器添加到你的显示页面。这是一个很容易解决你尝试做什么。
如果只有创作者可以编辑自己的帖子,那么您应该如何显示帖子,这对我来说很快就可以构建功能。
<tbody>
<% @posts.each do |post| %>
<tr>
<td><%= post.content %></td>
<td> - <%= post.user.username %> (<%= post.user.first_name %> <%= post.user.last_name %>)</td>
<% if post.user.id == @user %>
<td><%= link_to 'Edit', edit_post_path(post) %></td>
<td><%= link_to 'Delete', post, method: :delete, data: { confirm: 'Are you sure?' } %></td>
<% end %>
</tr>
<% end %>
</tbody>
在你的控制器中你需要做的就是添加这一行。
@user = current_user.id
很抱歉,现在已经很晚了,但希望将来有所帮助!
您可能还需要将以下内容添加到用户模型中。
accepts_nested_attributes_for :posts