Search code examples
ruby-on-railsruby-on-rails-4simple-form

undefined method path with simple form


I have albums and pictures where albums hasmany pictures

This is my routes.rb

 resources :albums do
  resources :photos
end

Instead of photos_path my path is album_photos_path In my photos/new.html.erb I'm getting this error:

undefined method photos_path' for #<#<Class:0x5232b40>:0x3cd55a0>

How I can do to instead of photos_path simple form write album_photos_path ?

My new.html.erb

<%= simple_form_for([@album, @photo]) do |f| %>
<%= f.error_notification %>

<div class="form-inputs">
<%= f.input :title %>
<%= f.input :description %>
</div>

<div class="form-actions">
<%= f.button :submit %>
</div>
<% end %>

Solution

  • You can specify url in your form. Like this:

    <%= simple_form_for @photo, url: album_photos_path do |f| %>
      <%= f.error_notification %>
    
      <div class="form-inputs">
        <%= f.input :title %>
        <%= f.input :description %>
      </div>
    
      <div class="form-actions">
        <%= f.button :submit %>
      </div>
    <% end %>
    

    But your code should also work. In your new action did you initialize both @album and @photo, something like:

    def new
      @album = Album.find params[:album_id]
      @photo = @album.pictures.build
    end
    

    P.S above code is just a sample code and if both variables(@album and @photo) are initialized properly then rails will automatically generate correct url.