HealthReport中的NoMethodError#new

时间:2016-10-09 13:30:29

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

当我想渲染表单

时,我一直收到此错误

错误指向<%= form_for(@hreport)do | f | %>,我不确定哪里出错或者我错过了什么,任何人的帮助都是值得欣赏的!

<div class="col-md-6 col-md-offset-3">

    <%= form_for(@hreports) do |f| %>

        <%= f.label :"Student ID" %>
        <%= f.text_field :studentid, class: 'form-control' %>

这是我的health_report_controller.rb

class HealthReportController < ApplicationController
  def index
    @hreports = Healthreport.where(:user_id => current_user.id)
  end

  def new
    @hreports = Healthreport.new
  end

  def create
    @hreports = current_user.healthreports.build(hreport_params)
    if @hreports.save
      flash[:success] = "Report Submitted!"
    else

    end

  end


  def show
    @hreports = Healthreport.find(params[:id])
  end


  private

  def set_hreport
    @hreport = Healthreport.find(params[:id])
  end

  # Never trust parameters from the scary internet, only allow the white list through.
  def hreport_params
    params.require(:Healthreport).permit(:date, :studentid, :department, :issue)
  end
end

这是我的观点

<% provide(:title, 'New Report') %>
<h1>Health and Safety Report</h1>

<div class="row">
  <div class="col-md-6 col-md-offset-3">

    <%= form_for(@hreports) do |f| %>

        <%= f.label :"Student ID" %>
        <%= f.text_field :studentid, class: 'form-control' %>

        <%= f.label :"Department of applicant" %>
        <%= f.text_field :department, class: 'form-control' %>

        <%= f.label :"Description of Issues" %>
        <%= f.text_area :issue, placeholder: "Write your report here...",  class: 'form-control' %>


        <%= f.submit "Submit", class: "btn btn-primary" %>
    <% end %>

这是我在model文件夹

中的healthreport.rb
class Healthreport < ApplicationRecord
  belongs_to :user
end

这是我在db文件夹

中的healthreport.rb
class CreateHealthreports < ActiveRecord::Migration[5.0]
  def change
    create_table :healthreports do |t|
      t.datetime :date
      t.string :studentid
      t.string :department
      t.string :issue

      t.timestamps
    end
  end
end

这是迁移db文件

class AddUserToHealthreport < ActiveRecord::Migration[5.0]
  def change
    add_reference :healthreports, :user, foreign_key: true
  end
end

1 个答案:

答案 0 :(得分:0)

在你的控制器中,你这样做:

def new
  @hreports = Healthreport.new
end

但在视图中,您期待这个

<%= form_for(@hreport) do |f| %>

您正在传递@hreports,但尝试使用@hreport。将控制器更改为

def new
  @hreport = Healthreport.new
end

(索引动作应使用复数,其他动作应使用单数)

你应该注意的两个Rails约会/风格的东西:

  1. 单个变量名称(例如@hreport)是指单个对象;该名称的复数形式(@hreports)是指数组或ActiveRecord关系。

  2. 模型和控制器应使用相同的命名样式:如果控制器名为health_report_controller.rb并定义HealthReportController,则模型文件应命名为health_report.rb并应定义HealthReport课程。