将form_for与嵌套资源一起使用。 “未定义的方法_index_path”

时间:2014-12-14 22:30:42

标签: ruby-on-rails ruby-on-rails-4

我尝试使用Carrierwave上传表单上的文件。到目前为止,我已经设法成功地“躲过了”。一个模型到另一个模型,但现在我很难做到' form_for'正确。

这个想法是设置一个页面(索引),列出对应于每个人(个人)的照片(Fotografias),并能够在同一页面中添加新的。

我有以下型号:

fotografia.rb

class Fotografia < ActiveRecord::Base
  belongs_to :individuo

  mount_uploader :title, ArchivoUploader
end

individuo.rb

class Individuo < ActiveRecord::Base
  has_many :fotografias
end

控制器:

fotografias_controller.rb

class FotografiasController < ApplicationController
  before_action :set_individuo, only: [:index, :show, :edit, :create, :update, :destroy]
  before_action :set_fotografia, only: [:show, :edit, :update, :destroy]

  def index
     @fotografias = @individuo.fotografias
     @new_foto = @individuo.fotografias.build
  end

  def set_individuo
    @individuo = Individuo.find(params[:individuo_id])
  end

  def set_fotografia
    @fotografias = Fotografia.find(params[:id])
  end

  def fotografia_params
    params.require(:individuo).permit(:individuo_id, :title)
  end
end

title是保存模型中文件信息的字段。

index.html.haml:

=form_for [@individuo,@new_foto] do |f|
  .row
    =f.file_field :title, :class => 'hidden'
    =f.label :title, 'New Fotografia', :class => 'btn btn-sm btn-primary'

我读到这可能是一个多元化的问题,但我不认为这是个案。这些是我的路线:

的routes.rb

  resources :individuos do
    resources :fotografias
  end

rake路由输出:

    individuo_fotografias GET    /individuos/:individuo_id/fotografias(.:format)          fotografias#index
                          POST   /individuos/:individuo_id/fotografias(.:format)          fotografias#create
 new_individuo_fotografia GET    /individuos/:individuo_id/fotografias/new(.:format)      fotografias#new
edit_individuo_fotografia GET    /individuos/:individuo_id/fotografias/:id/edit(.:format) fotografias#edit
     individuo_fotografia GET    /individuos/:individuo_id/fotografias/:id(.:format)      fotografias#show
                          PATCH  /individuos/:individuo_id/fotografias/:id(.:format)      fotografias#update
                          PUT    /individuos/:individuo_id/fotografias/:id(.:format)      fotografias#update
                          DELETE /individuos/:individuo_id/fotografias/:id(.:format)      fotografias#destroy

我为西班牙语命名法和其他语言混淆道歉。

当我尝试加载http://localhost:3000/individuos/3/fotografias时,我收到以下错误:&#34;#&lt;#:0x007fa05c5d44a0&gt;&#34;的未定义方法individuo_fotografia_index_path,错误行为{{1 }}

我失踪的任何线索?

解决方案

根据TK-421的回答,我对form_for进行了更改:

=form_for [@individuo,@new_foto] do |f|

这将确保它进入=form_for [@new_foto.individuo, @new_foto], :html => { :multipart => true }, :url => {:controller => 'fotografias', :action => 'create'} do |f| 控制器中的CREATE操作。为了彻底,这里是控制器中的创建动作:

fotografias_controller.rb

Fotografias

1 个答案:

答案 0 :(得分:1)

鉴于上面的路由输出和错误,似乎Rails正在寻找individuo_fotografias_path(而不是individuo_fotografia_index_path)。

但根据您提供的form_for示例,我不确定这是否是您的意图。

您可以尝试将url参数添加到表单助手中,以便更具体:url: individuo_fotografias_path

或以其他方式尝试doc中定义的辅助工具的一些较长形式选项,直到您按照自己喜欢的方式工作。

相关问题