# Automatic scoping in controller based on params\[\]

**URL:** <https://www.ruby-forum.com/t/automatic-scoping-in-controller-based-on-params/113948>\
**Category:** Rails\
**Created:** [September 6, 2007, 3:40pm UTC](https://www.ruby-forum.com/t/automatic-scoping-in-controller-based-on-params/113948 "2007-09-06T15:40:07Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Tarsoly\_AndrSSSSs](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/t/57b2e6/32.png) [@Tarsoly\_AndrSSSSs](https://www.ruby-forum.com/u/Tarsoly_AndrSSSSs)\
**Post date:** [September 6, 2007, 3:40pm UTC](https://www.ruby-forum.com/t/automatic-scoping-in-controller-based-on-params/113948/1 "2007-09-06T15:40:07Z")

</div>

Hi guys,

let’s say I have a nested route, like User \> Roles

# map.resources :user, :has\_many =\> [:roles]

In this case, calling new\_user\_role\_url gets me to the role  
controller’s :create method with a user\_id set in the parameters. Is  
there a better way to handle the creation of this role object  
automatically in the User object’s :roles association or I just have  
to resort to the good old method of finding the appropriate user  
object first and add the new role object to it’s association proxy:

# @user = User.find(params[:id])

# @user.roles \<\< Role.create(params[:role])

Any ideas would be appreciated.

Regards,  
AndrÃ¡s

–  
Tarsoly AndrÃ¡s  
removed\_email\_address@domain.invalid

---

<div class="post-metadata">

**Author:** ![Tarsoly\_AndrSSSSs](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/t/57b2e6/32.png) [@Tarsoly\_AndrSSSSs](https://www.ruby-forum.com/u/Tarsoly_AndrSSSSs)\
**Post date:** [September 25, 2007, 12:09am UTC](https://www.ruby-forum.com/t/automatic-scoping-in-controller-based-on-params/113948/2 "2007-09-25T00:09:41Z")

</div>

User.find(params[:user\_id]).roles.create(params[:role])

or

Role.create( params[:role].merge(:user\_id =\> params[:user\_id]) )

I would prefer the first way.

Sometimes is better to be more verbose

if user = User.find\_by\_id(params[:user\_id])  
user.create(params[:role])  
end

what you might want to do is something like this especially if the  
presence of the user is obbligatory:

before\_filter :get\_user  
private  
def get\_user  
@user = params[:user\_id] || current\_user  
raise YourOwnCustomError unless @user  
end  
public

def create  
@user.roles.create(params[:role])  
end

Diego

On 9/6/07, Tarsoly András [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid) wrote:

> ## object’s :roles association or I just have to resort to the good old method
> 
> Tarsoly András  
> removed\_email\_address@domain.invalid
> 
> >

–  
Diego Scataglini
