2

如何使用户只能使用 Devise 编辑/查看属于他们的项目?我似乎无法弄清楚。我研究并发现了一些关于在我的清单控制器索引中设置 current_user 并创建方法以及将关系放入我的用户模型和清单模型中的内容。我正在创建一个清单,用户可以在其中创建标题和名称,并将项目添加到该清单中,因此我也有一个项目模型。我读过关于康康舞的书,但不太确定这是否是我要找的。我只想在用户登录以创建清单时拥有它,该清单仅属于他们,因此当他们注销时,它不会显示他们创建的任何清单。当他们重新登录时,将显示创建的清单。我知道这是相当简单的事情,但无法确定任务。任何人都可以帮忙。我在这个项目上使用 rails 4。谢谢!

4

5 回答 5

2

权限有两个主要方面。身份验证和授权。

Devise提供了Authentication,基本上就是“这个用户就是这个人”。它通过登录验证这一点。

cancan这样的库有助于提供授权,即“允许此用户执行此操作”。您可以使用 cancan 来定义具有块的能力,以执行以下操作:

can :read, Item, Item.all do |item|
  item.owner == current_user
end  
于 2013-07-02T18:59:25.247 回答
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
于 2013-07-02T19:05:35.747 回答
2

我知道这是一篇很老的帖子,但要回答您的问题,您需要做的就是将过滤器添加到您的显示页面中。这很容易解决您尝试做的事情。

如果只有创建者可以编辑他们自己的帖子,那么您应该如何显示您的帖子,这对我来说可以快速构建功能。

<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

于 2015-06-14T20:54:13.313 回答
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 文档中

于 2013-07-02T19:02:38.260 回答
1

您必须将 user_id 外键放在要设置此限制的所有模型中。

和编辑和查看操作做这样的事情

例子 : -

用户 has_many :posts

并发布belong_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
于 2013-07-02T19:04:17.953 回答