2

如何限制可用于显示操作的记录?我遇到的问题是您可以手动更改 URL 中的 ID 并查看不属于公司的项目。

我的路线如下所示:

/companies/:id/projects/:id

这是表演动作

项目控制器.rb

def show
    @project = Project.find(params[:id])
    @company = Company.find(params[:company_id])
    respond_to do |format|
      format.html # show.html.erb
      format.json { render json: @project }
    end
end

路线.rb

resources :companies do
    resources :projects
    resources :employees
    resources :requests do
      put 'accept', :on => :member
    end
end

项目.rb

class Project < ActiveRecord::Base
  attr_accessible :title

  belongs_to :company

 validates :title, presence: true
end

公司.rb

类公司 < ActiveRecord::Base attr_accessible :name

has_many :projects

结尾

4

3 回答 3

2

假设您之间有has_many关系CompanyProject我会将您的控制器代码更改为:

def show
  @company = Company.find(params[:company_id])
  @project = @company.projects.find(params[:id])
end

Keep in mind though that this does not really solve your problem as people can still change the company_id and view other companies easily. What you need is a more solid authorization framework like CanCan that prevents unauthorized access to resources.

于 2012-07-03T09:58:47.600 回答
0

May be, you should use smth like this:

@project = @company.projects.find(params[:id])

Check this for details.

于 2012-07-03T09:59:29.970 回答
0

Try to change the action to this

def show
    @company = Company.find(params[:company_id])
    @project = @company.projects.find(params[:id])
    respond_to do |format|
      format.html # show.html.erb
      format.json { render json: @project }
    end
end
于 2012-07-03T10:14:05.787 回答