Nested resources on user not working as expected #516

timsjoberg opened this Issue Nov 20, 2011 · 1 comment


None yet

2 participants


So a user has many daily measurements, and users must not be able to see/alter other peoples daily measurements.

Shortened version of ability.rb:

class Ability
  include CanCan::Ability

  def initialize(user)
    can :create, DailyMeasurement, :user_id =>
    cannot :read, DailyMeasurement
    can :manage, DailyMeasurement, :user_id =>

Shortened DailyMeasurements controller

class DailyMeasurementsController < ApplicationController
  load_resource :user
  load_and_authorize_resource :daily_measurement, :through => :user

  def create
      redirect_to user_daily_measurements_url(@user), :notice => "Added measurement!"
    else = "Unable to create daily measurement"
      render :new

Firstly the user seems to be able to do everything if he navigates to another users daily measurements. But even stranger is below, when i'm logged in an the user with id 8, and playing around with the user with id 7's daily measurements. I've edited out the non-essential params to make it more readable:

Started POST "/users/7/daily_measurements" for at 2011-11-20 10:12:55 +0200
  Processing by DailyMeasurementsController#create as HTML
  Parameters: {..., "daily_measurement"=>{..., "user_id"=>"7"}
  User Load (0.2ms)  SELECT "users".* FROM "users" WHERE "users"."id" = $1 LIMIT 1  [["id", 8]]
  User Load (0.3ms)  SELECT "users".* FROM "users" WHERE "users"."id" = $1 LIMIT 1  [["id", "7"]]
   (0.1ms)  BEGIN
  SQL (0.6ms)  INSERT INTO "daily_measurements" ..., "user_id", ...) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11) RETURNING "id"  [..., ["user_id", 8], ...]
   (12.2ms)  COMMIT
Redirected to http://localhost:3000/users/7/daily_measurements
Completed 302 Found in 146ms

The action posts with user_id of 7, but at some point cancan seems to change it to 8?

The reason that someone can get to any user's measurements is that you are not authorizing the user. Presumbably, you have a current_user object somewhere, you need to take that into account in the ability, and then use "load_and_authorize_resource :user" rather than just "load_resource :user".

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment