我正在努力让User
能够编辑自己的Dashboard
。
我正在使用CanCan和Devise来尝试实现此目的(Rolify也会安装以帮助管理功能,但我觉得它不适用于这种情况)
当我有一个用户登录并且他们访问了他们的:root / users / id / dashboard.id上的show dashboard页面时,虽然它们与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
答案 0 :(得分:1)
请查看here
基本上,您希望使用load_resource
帮助程序方法仅获取current_user的仪表板。在幕后,它在你的控制器中做了类似的事情:
current_user.dashboard.find(params[:dashboard_id])