Thank u so much mike, that was exactly what I needed, however your
link didnt work :S
sorry, I should've been more descriptive with the link.. The link I
posted is the rails sample application. You can find the svn
repository for it here:
svn://caboo.se/plugins/court3nay/empty_apps/restful_auth_rspec
you should be able to issue an svn co to that url and obtain a local
copy of the sample application.
one more question, I added this to my routes.rb:
map.resources :users do |users|
users.resources :user_images
end
the convention for using nested resources would normally be to name
your nested controller simply 'images', since the nested declaration
implicitly shows that images belong to users. Also, the url generated
by the above would be '/users/<id>/user_images/<id>' which I think is
less attractive than '/users/<id>/images/</id>'
link in the view:
<%= link_to 'Add a picture', new_user_image_path(@user) %>
the weird thing comes in the new action in the user_image controller,
the only way I can find the user data is using this
def new
@user = User.find(@params[:user_id])
end
It only works when I use @params[:user_id] dont know why, if i try
@params[:user] or @params[:id] it will give me a Couldn't find Place
without an ID exception.
this is the expected behaviour for nested resources. When the nested
controller sees a request such as '/users/17/images/new', the id for
the user will be passed under params[:user_id]. If, however, you were
going to call the show action for an individual image, such as with
the following route: '/users/17/images/20', then you'd receive the
value 17 for params[:user_id] and 20 would be passed as params[:id].
When dealing with nested restful controllers, it's common to use a
before_filter in the nestee which grabs the parent object. For
example, in your images controller, you'd use the following:
before_filter :get_user
private
def get_user
@user = User.find_by_id(params[:user_id])
end
public
public restful methods go here
and then in your create method, you'd use something like:
def create
# no need to find the user, the before filter takes care of that
@image = @user.images.build(params[:image])
...
@image.save!
...
end
Again, a lot of this is covered in the caboo.se sample rails
application, although they make things more flexible by using a
polymorphic association, which means instead of using an 'images'
nested controller, they use 'assets' so a user can have any type of
file associated with them, it's not limited to just images.