【问题标题】:undefined method `model_name' in a partial rendered by different controller由不同控制器渲染的部分未定义方法“model_name”
【发布时间】:2013-08-13 14:34:16
【问题描述】:

我正在尝试渲染这个表单:

<form class="form-inline">
    <%= simple_form_for @prospect, 
    :url => url_for(:action => 'create', :controller => 'prospects'),
    :method => 'post' do |f| %>
    <%= f.error_notification %>
    <%= f.input :name,  placeholder: 'Name', label: false %>
    <%= f.input :email, placeholder: 'Email', label: false %>
    <%= f.input :interests, placeholder: 'Tell us what you were searching for', label: false, value: params[:search]  %>    
    <%= f.error :base %>
    <%= f.button :submit, "Submit", :class=> "btn" %>
<% end %>

使用这个部分:

 <%= render partial: 'prospects/novideo_capture' %>

部分位于由 Videos#index 控制器控制的视图中,我不断收到此错误:'undefined method `model_name' for NilClass:Class'

这是我的潜在客户控制器:

class ProspectsController < ApplicationController
  def index
    @prospects = Prospect.all
  end

  def new
    @prospect = Prospect.new
  end

  def create
    @prospect = Prospect.new(params[:prospect])
    if @prospect.save
    render "thanks_for_interest"
    else
    render "novideo_capture"
  end
end

我不确定我出了什么问题,尽管我很确定这是一个简单的解决方案。我已经看到了很多关于 SO 的类似问题,并尝试了他们所有的答案,但似乎没有一个适用于这种情况。

感谢您的帮助...

编辑:添加

@prospect = Prospect.new

到视频索引控制器会阻止错误发生,但我认为这不是正确的方法。它实际上也没有使表单使用前景控制器。

EDIT2:我现在正确地进行了部分渲染(我认为),并且我的视频#index 像这样调用部分:

 <%= render partial: 'prospects/novideo_capture', :prospect => @prospect %>

那么部分中的 simple_form 是这样的:

<form class="form-inline">
    <%= simple_form_for :prospect, 
    :url => url_for(:action => 'create', :controller => 'prospects'),
    :method => 'post' do |f| %>
 ...
<% end %>

但是,它实际上并没有向潜在客户控制器提交表单。任何想法为什么?

【问题讨论】:

  • 提交表单时控制台中显示的任何内容?
  • 是的,但由于某种原因它正在由 video#index 控制器处理,尽管它正在获取我正在提供的参数信息:由 VideosController#index 作为 HTML 参数处理:{“utf8” =>"✓", "authenticity_token"=>"PvgOtUlXxzTp6hNZNSNtO8AyPXx0GP1dNfLi4ZJ+72I=", "prospect"=>{"name"=>"Test", "email"=>"test@test.com", "interests"= >“测试”},“提交”=>“提交”}

标签: ruby-on-rails-3 partial-views simple-form controllers


【解决方案1】:

检查您的标记。您将 simple_form 包装在另一个表单中。由于第一个表单标记没有与之关联的操作 (&lt;form class="form-inline"&gt;),因此该表单将针对当前 URL(即 video#index)提交。

你会想要这样的东西:

<%= simple_form_for :prospect, :url => etc, :method => 'post', :class => "form-inline" do |f|
  ...
<% end %>

失去前导(冗余)表单内联表单标签,你会没事的。

【讨论】:

  • 谢谢,我就知道会很明显!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-10-07
  • 1970-01-01
  • 2021-09-23
  • 1970-01-01
  • 2016-02-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多