未定义的方法`内容&#39;对于#<note id:=“”nil,=“”created_at:=“”nil,=“”updated_at:=“”nil =“”>

时间:2015-08-09 09:50:21

标签: html ruby-on-rails ruby

我似乎之前发布了这个问题,但是正常的&#34;添加:内容到模型&#34;对我的情况不起作用。我已经添加了它,但错误仍然存​​在。

这是codecademy项目的修改版本,如果它看起来很熟悉。

模型

 class CreateNotes < ActiveRecord::Migration
    def change
      create_table :notes do |t|
        t.text :content
        t.timestamps
      end
    end
 end

控制器

class NotesController < ApplicationController
    def index
       @notes = Note.all
    end

    def new
       @note = Note.new
    end

    def create
       @note = Note.new(note_params)
           if @note.save
               redirect_to '/notes'
           else
               render 'new'
           end
    end

    private
    def note_params
       params.require(:note).permit(:content)
    end
end

路线

Rails.application.routes.draw do

     root 'notes#index'
     get "notes" => "notes#index"
     get "notes/new" => "notes#new"
     post "notes" => "notes#create"

index.html.erb

<div class="header">
  <div class="container">
    <h1>Notes</h1>
  </div>
</div>

<div class="notes">
  <div class="container">

    <% @notes.each do |note| %>
        <div class="note">
        <p class="content"><%= note.content %></p>
        <p class="time"><%= note.created_at %></p>
        </div>
    <% end %>
    <%= link_to 'New Note', "notes/new" %>

  </div>
</div>

new.html.erb

<div class="header">
  <div class="container">
    <h1>Notes</h1>
  </div>
</div>

<div class="create">
  <div class="container">

    <%= form_for(@note) do |f| %>
        <div class="field">
            <%= f.label :note %><br>
            <%= f.text_area :content %>
        </div>
        <div class="actions">
            <%= f.submit "Create" %>
        </div>
        <% end %>
  </div>
</div>

如果有人能弄清楚为什么我之后仍然会收到此错误:内容已经在模型中,那就太棒了!

P.S。第一篇文章很抱歉,如果它很糟糕。

1 个答案:

答案 0 :(得分:0)

ActiveRecord通过检查数据库中的列来在模型上创建方法content。由于该方法未定义,我认为您可能忘记了运行迁移。

该列不存在的可能原因:

  • 在运行迁移和运行应用程序时,您没有连接到同一数据库。例如,您可能在不同的环境中运行。
  • 您的迁移实际上并未添加所需的列。检查您的迁移。

可能的检查方式:

  • “手动”检查数据库以确认该列实际存在。