I am currently working on a web app for social networking site but it seems as if getting my nested resources to work correctly is impossible. If you can help me out that would be great and I would be very thankful.
Here are my routes. I would like to have the url structure like mysite.com/username/photos /(new, edit, etc). The url structure is like so but I get an error when trying to access the forms or page. Down below I have posted what I have so far.
routes.rb
resources :users do
resources :photos
end
photo.rb
belongs_to :users
user.rb
has_many :photos, :foreign_key => "id", :dependent => :destroy
_form.html.erb
This form has an attachment using paperclip. There is a <% before statement I removed it because it would not show the entire code below on here.
form_for(@photos,@user) :html => {:multipart => true} do |f| %>
photos_controller.rb
def new
@photo = Photo.new(params[:photo])
end
You need to create a before_filter to get the user, and the form posts to create, not new. Your photo controller should look something like:
Here, the before_filter grabs the user. In nested routes, the parent resource ID will be in
params[:parent_id]or in this case,params[:user_id]. Then inside the create controller, you want to build a photo from the@user.photoscollection. This will automatically create the reference between the photo and the user.Also, your form_for has the relations backwards. It should be
form_for([@user, @photo]) ..., not the other way around.