Search code examples
ruby-on-railsinstantiationnomethoderror

Instantiate new object on index page in Rails 4


simple question that I am not able to solve some how.

I am trying to mimic the first few steps of this Railscast Episode. I have a picture-Model and I am trying to instantiate an object of this kind on the index page. Therefor I am using those lines:

index.erb.html

<%= form_for Picture.new do |f| %>
    <%= f.label :image, "Upload" %>
    <%= f.file_field :image, multiple: true %>
<% end %>

But I am getting this error:

undefined method `pictures_path' for #<#<Class:0xb465af0>:0x58fc488>

If I remove the form it works perfectly. Seems simple but I can't solve it. I would appreciate some help.

PicturesController

class PicturesController < ApplicationController
  respond_to :html

  def index
    @house = House.find(params[:house_id])
    @pictures = @house.pictures
    respond_with(@pictures)
  end

  def new
    @picture = Picture.new
  end

  def create
  end

  def destroy
  end

  private

  def picture_params
    params.require(:picture).permit(:id, :name, :house_id, :image, :_destroy)
  end

routes.rb

Rails.application.routes.draw do

  resources :houses do
      resources :pictures, only: [:index]
  end
end

Solution

  • With your given routes info, you don't really have pictures_path. You have only these routes (if you do a rake routes):

    house_pictures GET    /houses/:house_id/pictures(.:format) pictures#index
            houses GET    /houses(.:format)                    houses#index
    

    That's why you are getting that error.

    You have access to house_pictures_path BUT NOT pictures_path.

    To solve this issue, you have to use house_pictures_path and send the @house and @pictures as argument to that. something like this:

    <%= form_for [@house, @house.pictures.build] do |f| %>
        <%= f.label :image, "Upload" %>
        <%= f.file_field :image, multiple: true %>
    <% end %>