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
[email protected]
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 [email protected] wrote:
object’s :roles association or I just have to resort to the good old method
Tarsoly András
[email protected]
–
Diego Scataglini