Rails Resources 访问控制

danjiang · 2014年12月25日 · 1441 次阅读

一个学校有很多个相册,一个用户只在一个学校,如何控制用户查看相册时候是它所属的学校的相册,下面这种做法在很多地方都会重复,有没有好一点解决办法

resources :school_albums do
    resources :school_album_images, :except => :show
end

def show
    @album = SchoolAlbum.find(params[:id])
    redirect_to root_path if @album.school_id != current_user.schools.first.id
    @images = @album.school_album_images.order("time DESC")
end

好一点的解决办法

app/models/concerns/school_visible.rb

module SchoolVisible
    extend ActiveSupport::Concern

    def visible_to(user)
        raise CanCan::AccessDenied if self.school_id != user.school.id
    end
end

app/models/school_ablum.rb

class SchoolAlbum < ActiveRecord::Base
    self.table_name = "school_album"
    belongs_to :school, :foreign_key => "school_id"
    has_many :school_album_images, :foreign_key => "album_id", :dependent => :destroy

    validates :title, :presence => true, :length => { :maximum => 14 }
    include SchoolVisible
end
def show
    @album = SchoolAlbum.find(params[:id])
    @album.visible_to(current_user)
    @images = @album.school_album_images.order("time DESC")
end
1 楼 已删除
需要 登录 后方可回复, 如果你还没有账号请 注册新账号