0

我正在尝试制作一个User能够编辑自己的Dashboard.

我正在使用CanCanDevise来尝试实现这一点(还安装了Rolify以帮助使用管理功能,但我认为它不适用于这种情况)。

当我有一个用户登录并且他们访问他们的 :show 仪表板页面时,他们在 root/users/id/dashboard.id 上进行了身份验证,尽管它们与user.id列出的相同dashboard.user_id(如ability.rb文件中所述)。

如何确保用户可以查看自己的仪表板?

以下是相关代码:

dashboards_controller.rb

class DashboardsController < ApplicationController
  before_filter :authenticate_user!

  def show
    @dashboard = Dashboard.find(params[:format])
    authorize! :read, current_user, :message => 'Not authorized to view this dashboard.'
  end
 end

ability.rb

user ||= User.new

if user.has_role? :default # All of my users have this role
    can :read, Dashboard, :user_id => user.id
end

routes.rb

resources :users do
  resource :dashboard, only: [:show, :edit, :update, :destroy]
end

User.rb

#  id                     :integer          not null, primary key
#  email                  :string(255)      default(""), not null
#  encrypted_password     :string(255)      default(""), not null
#  reset_password_token   :string(255)
#  reset_password_sent_at :datetime
#  remember_created_at    :datetime
#  sign_in_count          :integer          default(0)
#  current_sign_in_at     :datetime
#  last_sign_in_at        :datetime
#  current_sign_in_ip     :string(255)
#  last_sign_in_ip        :string(255)
#  created_at             :datetime
#  updated_at             :datetime
#
class User < ActiveRecord::Base
  rolify
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

  has_one :dashboard
  before_create :build_dashboard

end

Dashboard.rb

# Table name: dashboards
#
#  id                        :integer          not null, primary key
#  user_id                   :integer
#  has_selected_account_type :boolean          default(FALSE)
#  created_at                :datetime
#  updated_at                :datetime
#
class Dashboard < ActiveRecord::Base
    belongs_to :user
end
4

1 回答 1

1

请看这里

基本上,您想使用load_resource辅助方法仅获取 current_user 的仪表板。在幕后,它在您的控制器中执行以下操作:

current_user.dashboard.find(params[:dashboard_id])
于 2013-07-01T18:24:10.377 回答