我在rails blog專案中做了Authentication,但是登陸網站的,也就是ad??min可以編輯和destroy,guest用戶不能編輯destroy。我對rails很陌生,我不知道要添加什么。以及如何讓訪客用戶登錄?來賓用戶只讀。
索引.html
<div class="container">
<div class="row">
<% @articles.each do |article| %>
<div class="col-md-6">
<div class="row g-0 rounded overflow-hidden shadow-lg h-md-250">
<div class="col p-4 d-flex flex-column">
<strong class="mb-2 text-primary"><%= article.title %></strong>
<h3 class="mb-0"></h3>
<div class="mb-1 text-muted"><%= article.created_at.strftime("%d.%m.%Y %H:%M") %>
</div>
<p><%= article.text.truncate(110) %></p>
<div>
<%= link_to "Read more", article_path(article)%><br/><br/>
<tr>
<%= link_to 'Show', article_path(article),class:"btn btn-outline-success btn-sm"%>
<%= link_to 'Edit', edit_article_path(article),class:"btn btn-outline-warning btn-sm"%>
<%= link_to 'Destroy', article_path(article),class:"btn btn-outline-danger btn-sm",
method: :delete,
data: { confirm: 'Are you sure?' } %>
</tr>
</div>
</div>
</div>
</div>
<% end %>
</div>
<br/><br/>
<%= link_to 'New article', new_article_path,class:"btn btn-dark" %>
<%# sayfada show, edit, destroy butonlar? aktive oldu %>
</div>
application_controller.rb
class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
before_action :authenticate_user!
end
文章控制器.rb
class ArticlesController < ApplicationController
def index
@articles = Article.all
end
def show
@article = Article.find(params[:id])
end
def new
@article = Article.new
end
def edit
@article = Article.find(params[:id])
end
def create
@article = Article.new(article_params)
if @article.save
redirect_to @article
else
render 'new'
end
end
def update
@article = Article.find(params[:id])
if @article.update(article_params)
redirect_to @article
else
render 'edit'
end
end
def destroy
@article = Article.find(params[:id])
@article.destroy
redirect_to articles_path
end
private
def article_params
params.require(:article).permit(:title, :text)
end
end
uj5u.com熱心網友回復:
你還沒有提到你是如何實作身份驗證的——我假設你通過查看你的代碼添加了 gem Devise,但無論如何你必須以某種方式存盤每個用戶的角色。例如,將管理列添加到您的用戶模型
rails g migration AddsAdminColumnToUsers
def change
add_column :users, :admin, :boolean, default: false, null: false
end
然后在您的視圖和控制器中強制執行此要求
<% if current_user.admin? %>
<%= link_to 'Edit', edit_article_path(article),class:"btn btn-outline-warning btn-sm"%>
<%= link_to 'Destroy', article_path(article),class:"btn btn-outline-danger btn-sm",
method: :delete,
data: { confirm: 'Are you sure?' } %>
<% end %>
class ArticlesController < ApplicationController
def destroy
raise "unauthorized" unless current_user.admin?
@article = Article.find(params[:id])
@article.destroy
redirect_to articles_path
end
def edit
raise "unauthorized" unless current_user.admin?
...
end
end
許多人使用像 Rolify 和 CanCan 這樣的 gem,但是對于簡單的需求,這種方法可以在沒有任何 gem 的情況下作業。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/482380.html
標籤:轨道上的红宝石 红宝石 ruby-on-rails-5
