link_to on an unsaved association in a loop causing path error

I have a link_to inside of an each loop. The object that's being looped does indeed contain a new record (sometimes). The parent object is a book and the nested object is photo.

- @book.photos.each do |photo|
  = link_to image_tag(photo.pic.url), edit_book_photo_path(@book)

And the error is, rather predictably:

No route matches {:action=>"edit", :controller=>"photos", :id=>nil, :book_id=>147, :format=>nil} missing required keys: [:id]

I have tried checking for a new_record using:

- @book.photos.each do |photo|
  = link_to image_tag(photo.pic.url), edit_book_photo_path(@book) unless photo.new_record?

And

- @book.photos.each do |photo|
  - unless photo.new_record?
    = link_to image_tag(photo.pic.url), edit_book_photo_path(@book) 

But get the same error.

That unless works fine if I'm not doing a link_to, for instance if I create a list

%ul
  - @book.photos.each do |photo|
    - unless photo.new_record?
      %li= "This is id #{photo.id}"

I see see that there are the correct number of child objects and removing the unless gives me one extra with no id.

So, clearly I'm making this overly complicated, because it should be simple or I've gone astray. The GOAL::: Render a list of images (@book.photos.pic) on the book's form, each image is a link to edit the photo record.

Suggestion?

Answers


- @book.photos.select(&:persisted?).each do |photo|
  = link_to image_tag(photo.pic.url), edit_book_photo_path(@book, photo)

Try adding picture id:

- @book.photos.each do |photo|
  = link_to image_tag(photo.pic.url), edit_book_photo_path(@book, photo)

Need Your Help

How to cancel a sequence of UITouch events?

iphone ios uitouch touchesmoved uiresponder

I have a UIImage view that responds to touch events. I want to cancel the touch sequence, i.e., further calls to touchesMoved:, if the touch goes outside of certain bounds. How can I do that?

Plugin manager not working in netbeans 7.0.1

netbeans

On upgrading from netbeans 6.9 to 7.0.1, my plugins are not visible in the plugins manager. But more importantly, I am not even able to install new plugins, or watch the avaialble plugins. No plugi...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.