Lew*_*ost 2 ruby ruby-on-rails ruby-on-rails-3
我有一个用户模型和一个问题模型.
在用户模型中:
has_many :questions
Run Code Online (Sandbox Code Playgroud)
问题模型:
belongs_to
Run Code Online (Sandbox Code Playgroud)
在我的问题/ show.html.erb
<% if @question.user == current_user %>
<%= link_to 'Edit', edit_question_path(@question) %> | <%= link_to 'Destroy', @question, method: :delete, data: { confirm: 'Are you sure you want to delete this job?' } %>
<%= link_to 'Back', questions_path %>
<% else %>
<%= link_to 'Back', questions_path %>
<% end %>
Run Code Online (Sandbox Code Playgroud)
只有编写问题的用户如何编辑并删除它?
看看CanCan,Railscasts的Ryan Bates的授权宝石.这对Rails授权需求非常有用.
首先,您将创建一个Ability定义应用程序中所有功能的类.
class Ability
include CanCan::Ability
def initialize(user)
can :manage, Question, user_id: user.id
end
end
Run Code Online (Sandbox Code Playgroud)
然后,您将能够轻松地将授权集成到您的控制器中.
class QuestionsController < ApplicationController
def update
authorize! :manage, @question
...
end
def destroy
authorize! :manage, @question
...
end
end
Run Code Online (Sandbox Code Playgroud)
并定制您的观点.
<% if can? :manage, @question %>
<%= link_to 'Edit', edit_question_path(@question) %> | <%= link_to 'Destroy', @question, method: :delete, data: { confirm: 'Are you sure you want to delete this job?' } %>
<% end %>
Run Code Online (Sandbox Code Playgroud)