我有一個索引頁面,通過使用布爾值來隱藏/顯示不同的作者。我遇到的問題是登錄的用戶仍然可以通過URL訪問隱藏的作者和他們的書籍。阻止用戶瀏覽隱藏的作者
如何防止當前用戶通過URL導航到隱藏的作者及其相應書籍?如果作者隱藏,是否有辦法將他們重定向回作者頁面?
目前,我使用控制器&布爾值來幫助隱藏/顯示作者或書籍從登錄用戶。有人可以請我指出正確的方向。這是我的代碼。
MODELS
class Author < ActiveRecord::Base
attr_accessible :name, :photo
has_many :books
end
class Book < ActiveRecord::Base
attr_accessible :author_id, :title, :photo
belongs_to :author
end
CONTROLLERS
class AuthorsController < ApplicationController
before_filter :signed_in_user, only: [:index]
before_filter :admin_user, only: [:edit, :update, :destroy, :new, :show]
respond_to :html, :js
###Only displays unhidden authors to non admin users.
def index
if current_user.admin?
@authors = Author.all(:order => "created_at")
else
@authors = Author.where(:display => true).all(:order => "created_at")
end
end
private
def signed_in_user
unless signed_in?
store_location
redirect_to (root_path), notice: "Please sign in."
end
end
def admin_user
redirect_to(root_path) unless current_user.admin?
end
end
class BooksController < ApplicationController
before_filter :signed_in_user, only: [:index]
before_filter :admin_user, only: [:edit, :update, :destroy, :new, :show]
before_filter :get_author
respond_to :html, :js
def get_author
@author = Author.find(params[:author_id])
end
def index
@books = @author.books
end
private
def signed_in_user
unless signed_in?
store_location
redirect_to (root_path), notice: "Please sign in."
end
end
def admin_user
redirect_to(root_path) unless current_user.admin?
end
end
VIEWS
Authors index.html.erb
<% @authors.each do |author| %>
<%= link_to (image_tag author.photo(:medium)),
url_for(author_books_path(author)),
class: "img-rounded" %>
<% end %>
### How Can I prevent Users from accessing Hidden Author's Books (Index Page)
Books index.html.erb
<% @books.each do |book| %>
<%= image_tag book.photo(:medium) %>
<%= book.name %>
<% end %>
個ROUTES
resources :authors do
resources :books
end
SCHEMA
create_table "authors", :force => true do |t|
t.string "name"
t.boolean "display", :default => false
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
t.string "photo_file_name"
t.string "photo_content_type"
t.integer "photo_file_size"
t.datetime "photo_updated_at"
end
create_table "books", :force => true do |t|
t.integer "author_id"
t.string "title"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
t.string "photo_file_name"
t.string "photo_content_type"
t.integer "photo_file_size"
t.datetime "photo_updated_at"
end