0
votes

I have an Items model that has_many Photos (which belongs_to Items), both namespaced under Admin. Uploading via the form works as expected via the Photo's new or edit action(, but not when rendered from the Item show page, I get an "undefined method `model_name' for NilClass:Class" error.When I create a new photo record I pass in the item_id and I'm not sure what to pass into the form on the items page.

PhotosController;

  class Admin::PhotosController < Admin::BaseController
  def new
      @photo = Photo.new(:item_id => params[:item_id])
    end

  def create
    @photo = Photo.new(params[:photo])
    if @photo.save
      flash[:notice] = "Successfully created photo."
      redirect_to [:admin,@photo.item]
    else
      render :action => 'new'
    end
  end

  def edit
    @photo = Photo.find(params[:id])
  end

  def update
    @photo = Photo.find(params[:id])
    if @photo.update_attributes(params[:photo])
      flash[:notice] = "Successfully updated photo."
      redirect_to [:admin,@photo.item]
    else
      render :action => 'edit'
    end
  end

  def destroy
    @photo = Photo.find(params[:id])
    @photo.destroy
    flash[:notice] = "Successfully destroyed photo."
    redirect_to [:admin,@photo.item]
  end
end

photos/_form.html.haml;

= form_for [:admin,@photo], :html => {:multipart => true,id: 'upload'} do |f|
  = f.hidden_field :item_id
  %p
    = f.label :name
    %br/
    = f.text_field :name
  %p
    = file_field_tag :image, multiple: true, name:'photo[image]',id: 'photo_image'
  %p= f.submit

items/show.html.haml;

= render 'admin/photos/form'
2

2 Answers

0
votes

doh! figured it out the render call should be;

= render 'admin/photos/form', :photo => @item.photos.build

and the form

 = form_for [:admin,photo]
0
votes

or you can create a @photo variable in your items_controller#show like

@photo = @item.photos.build 

and in your partial

form_for[:admin,@photo]

i think this would be better, because all of your variables get assigned in the controller and not one in the controller and the other in the view.