2

How can you limit the records that are available to the show action? The problem I'm having is that you can manually change the ID in the URL and look at projects that do not belong to the company.

My Routes Look like this:

/companies/:id/projects/:id

This is the show action

projects_controller.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

routes.rb

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

project.rb

class Project < ActiveRecord::Base
  attr_accessible :title

  belongs_to :company

 validates :title, presence: true
end

company.rb

class Company < ActiveRecord::Base attr_accessible :name

has_many :projects

end

AgentSpyname
  • 105
  • 1
  • 9
Aaron Dufall
  • 1,177
  • 10
  • 34

3 Answers3

2

Assuming you have a has_many relationship between Company and Project I would change your controller code to this:

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.

Tigraine
  • 23,358
  • 11
  • 65
  • 110
  • So I can leave it open as is and impliment the access through authorisation? – Aaron Dufall Jul 03 '12 at 12:31
  • I would still do both to prevent users who have access to multiple companies to see project from company b inside company a's layout (in case they mess with the params) not really necessary but also not hard to do ;) – Tigraine Jul 03 '12 at 22:24
0

May be, you should use smth like this:

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

Check this for details.

tiktak
  • 1,801
  • 2
  • 26
  • 46
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
Pritesh Jain
  • 9,106
  • 4
  • 37
  • 51