Rails 4:如何让用户只查看自己办公室中的文件

时间:2015-06-17 01:11:15

标签: ruby-on-rails

我正在创建一个文件跟踪系统,用户可以跟踪从一个办公室到另一个办公室的移动。我已经完成了大部分应用程序的工作,但是目前每个用户都可以查看所有文件,无论文件位于何处,都可以查看文件索引。

我在文件索引操作中使用File.all。有没有办法让用户只能查看和跟踪当前只在自己办公室的文件,而注册管理员(admin)可以查看和跟踪所有文件?

模特之间的关系:

文件模型

class Nasfile < ActiveRecord::Base
  belongs_to :category
  has_many :trackers, dependent: :destroy


  before_save :file_full_number, :on => [:create, :update] 
    def file_full_number
        if self.file_sub.present?
            self.file_number = [self.file_number , self.file_sub].join('/')
        else
            self.file_number = self.file_number
        end
    end
end

办公室模型

class Office < ActiveRecord::Base
  belongs_to :department

  has_many :users
  has_many :received_files,:class_name => 'Tracker', :foreign_key => 'office_sent_to_id'
  has_many :sent_files,:class_name => 'Tracker', :foreign_key => 'office_sent_from_id'


  def self.all_without(excluded)
    where("id NOT IN (?)", excluded)
  end
end

追踪模型

class Tracker < ActiveRecord::Base
  belongs_to :nasfile

  belongs_to :sender, :foreign_key => :sender_id, class_name: 'User'
  belongs_to :receiver, :foreign_key => :receiver_id, class_name: 'User'
  belongs_to :office_receiving, :foreign_key => :office_sent_to_id, class_name: 'Office'
  belongs_to :office_sending, :foreign_key => :office_sent_from_id, class_name: 'Office'


  before_save :office_sent_to, :on => [:create, :update] 

    def office_sent_to      
        self.office_sent_to_id = self.receiver.office.id        
    end     

end

用户模型:

class User < ActiveRecord::Base
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable,:recoverable
  devise :database_authenticatable, :registerable,
         :rememberable, :trackable, :validatable,
         :authentication_keys => [:username], password_length: 6..25

  belongs_to :office
  accepts_nested_attributes_for :office

  has_many :sent_files,:class_name => 'Tracker', :foreign_key => 'sender_id'
  has_many :received_files,:class_name => 'Tracker', :foreign_key => 'receiver_id'

  def email_required?
    false
  end

  def email_changed?
    false
  end

  def self.all_without(excluded)
    where("id NOT IN (?)", excluded)
  end

end

感谢您的帮助

1 个答案:

答案 0 :(得分:0)

而不是做

@files = File.all

尝试通过执行以下操作来过滤您包含的文件:

@files = File.where("office_id = ?", current_user.office_id)

这样,您只能获取用户所在办公室的文件。

我不知道您如何设置角色,但是您可以添加一些分支逻辑,以允许注册管理机构人员查看所有文件,无论办公室如何:

if user.role = "registry officer"
  @files = File.all
else
  @files = File.where("office_id = ?", current_user.office_id)
end