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 call NetUserModalsGet() from C#.NET?

c# .net winapi unmanaged

EDIT: followup at NetUserModalsGet() returns strings incorrectly for C#.NET

R: Simple anova with MANY factor values

r

I am attempting a simple anova with many factor values 7000+. Upon attempting to use the aov command, my computer is getting extremely bogged down (never finishing). I don't understand why this sho...