0

我有一个包含多个照片(属于_to Items)的 Items 模型,两者都在 Admin 下命名。通过照片的新或编辑操作(但不是从项目显示页面呈现时,通过表单上传按预期工作,我收到“NilClass:Class 的未定义方法 `model_name'”错误。当我创建新照片记录时,我传入 item_id ,我不确定将什么传递到项目页面上的表单中。

照片控制器;

  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

照片/_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

项目/show.html.haml;

= render 'admin/photos/form'
4

2 回答 2

0

doh! figured it out the render call should be;

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

and the form

 = form_for [:admin,photo]
于 2013-05-07T11:28:12.120 回答
0

或者您可以在 items_controller#show 中创建一个 @photo 变量,例如

@photo = @item.photos.build 

在你的部分

form_for[:admin,@photo]

我认为这会更好,因为您的所有变量都在控制器中分配,而不是控制器中的一个和视图中的另一个。

于 2013-05-07T11:31:43.967 回答