我想创建一个自定义路线,例如“ photos /:user_id /:photo_id”以显示每张照片。在我的路线文件中,我有;
get 'photos/:user_id/:photo_id' => 'photos#show', :as => 'user_photo'
并rake routes
给了我
user_photo GET /photos/:user_id/:photo_id(.:format) photos#show
编辑;
现在,当我使用链接到照片时link_to 'some photo', user_photo_path(@photo,@user)
,出现以下错误
Processing by PhotosController#show as HTML
Parameters: {"user_id"=>"8", "photo_id"=>"8"}
User Load (0.6ms) SELECT "users".* FROM "users" WHERE "users"."id" = 8 ORDER BY "users"."id" ASC LIMIT 1
Completed 404 Not Found in 3ms
ActiveRecord::RecordNotFound - Couldn't find Photo without an ID:
activerecord (4.1.1) lib/active_record/relation/finder_methods.rb:402:in `find_with_ids'
activerecord (4.1.1) lib/active_record/relation/finder_methods.rb:68:in `find'
activerecord (4.1.1) lib/active_record/querying.rb:3:in `find'
() Users/batman/code/myapp/app/controllers/photos_controller.rb:73:in `set_photo'
您需要将其添加到参数中:
link_to 'some photo', user_photo_path(@photo.user, @photo)
第二个错误是由您寻找照片的方式引起的。您最有可能做到:
photo = Photo.find(params[:id])
在这种情况下,您需要更改params[:id]
为parmas[:photo_id]
(如果这样做可能会制动其他动作,before_filter
或者将您的路线更改为:
get 'photos/:user_id/:id' => 'photos#show', :as => 'user_photo'
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句