Aaron Dufall Aaron Dufall - 4 months ago 17
Ruby Question

Matching records to nested routes in show action

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

Answer

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.