【问题标题】:undefined method `model_name' for nil:NilClass problem with simple_form form用于 nil 的未定义方法“model_name”:simple_form 形式的 NilClass 问题
【发布时间】:2019-05-20 11:09:17
【问题描述】:

simple_form 会产生问题:

我会解释我做了什么:我有 2 个脚手架:

问题/_form.html.erb

<%= simple_form_for(@question ) do |f| %>
  <%= f.error_notification %>
  <div class="field">
    <div class="control">
      <%= render "info_users" %>

      <%= f.input :question, label: "Quelle est votre question ou votre suggestion ?", input_html: { class: "textarea "}, wrapper: false, label_html: {class: "label"}, placeholder: "Commencez vos Questions par << Comment >>, << Pourquoi>>, << Que >>, etc...", autofocus: true %>
    </div>
  </div>
  <%= f.button :submit,'Ajouter Une Question', class: "button is-info is-rounded " %>
<% end %>

课程/_form.html.erb

<%= simple_form_for(@course) do |f| %>
  <%= f.error_notification %>    
  # here go all inputs
  <%= f.button :submit," Créer le Cours" ,class: "button is-info is-large is-rounded" %>
<% end %>

现在我在我的主页视图中使用这两个表单,这就是 simple_form 成为问题的时候。这是home/_feed.html.erb中partials的调用代码

注意:我在 home 中创建了部分 _feed.html.erb 以在 index.html.erb 中呈现它

主页/_feed.html.erb

<% if user_signed_in? %>
  <article class="media box">
    <div class="media-content">
      <%= render :partial => "questions/form" %>
    </div>
    <div class="media-content">
      <%= render :partial => "courses/form" %>
    </div>
  </article>
<% end %>

【问题讨论】:

  • 您是否定义了@question .. 错误来自此,未定义或设置为nil。检查您的控制器操作,
  • 你能发布控制器代码吗?这将有助于理解为什么将@question 设置为nil
  • 那是一大堆噪音。请将您的帖子删减到相关的细节,因为目前有大量信息与您的问题无关

标签: ruby-on-rails simple-form


【解决方案1】:

你可能没有在QuestionsController中设置新问题

def new
  @question = Question.new
end

【讨论】:

    【解决方案2】:

    您没有为表单定义 @question@course,因为现在您从 HomeController#index 渲染它们。此外,在局部变量中使用实例变量也是一个坏主意,因为很难说它们从哪里来的局部变量。只使用局部变量并将它们传递给局部变量

    # questions/_form.html.erb    
    <%= simple_form_for(question) do |f| %>
      # form code goes here
    <% end %>
    
    # the same for courses/_form.html.erb, change @course to course
    
    # home/_feed.html.erb    
    <%= render partial: "questions/form", question: @question %>
    <%= render partial: "courses/form", course: @course %>
    

    在 home_controller.rb 中定义实例变量

    def index
      @question = current_user.questions.new # I suppose you want to create associated records
      @course = current_user.courses.new
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多