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

Answers


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.


May be, you should use smth like this:

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

Check this for details.


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

Need Your Help

Why does a job fail with "No space left on device", but df says otherwise?

apache-spark

When performing a shuffle my Spark job fails and says "no space left on device", but when I run df -h it says I have free space left! Why does this happen, and how can I fix it?

How to get "geolocation" permission inside sandbox of chrome app

google-chrome-app sandbox google-geolocation

I have a chrome app with permissions set one of which is geolocation.