ryanb/cancan — Issue #516: Nested resources on user not working as expected
Author: timsjoberg
Created: 2011-11-20 08:38:30+00:00
State: open

Hi

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:

```ruby
class Ability
include CanCan::Ability

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

Shortened DailyMeasurements controller

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

def create
if @daily_measurement.save
redirect_to user_daily_measurements_url(@user), :notice => "Added measurement!"
else
flash.now.alert = "Unable to create daily measurement"
render :new
end
end
end
```

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 127.0.0.1 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?