未定义的方法'model_name'用于nil:NilClass问题,具有simple_form形式

时间:2019-05-20 11:09:17

标签: ruby-on-rails simple-form

simple_form产生了一个问题:

screenshot errors

我将解释自己的工作:我有2个脚手架:

questions / _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 %>

courses / _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

中的局部调用代码

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

home / _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 %>

2 个答案:

答案 0 :(得分:0)

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

def new
  @question = Question.new
end

答案 1 :(得分:0)

您没有为表单定义@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