未初始化的常量PostsController :: Post

时间:2014-05-28 17:55:42

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

/config/routes.rb

Rails.application.routes.draw do

  devise_for :users

  root 'posts#hello'

  resources :users
  resources :posts

end

/app/controllers/posts_controller.rb

class PostsController < ApplicationController

  before_filter :authenticate_user! , except: [:hello]

  def hello
  end

  def new
  end

  def create
    @post = Post.create(inner)
    redirect_to post_path(@post.id)
  end

  def index
    @posts = Post.all.order('id desc')
  end

  def show
    @post = Post.find_by(id: params[:id])
  end

private 

  def inner 
    params.require(:post).permit(:title, :desc)
  end

end

当我点击 posts_path 链接时,出现错误:未初始化的常量PostsController ::发布app / controllers / posts_controller.rb,第17行

def index
  @posts = Post.all.order('id desc')
end

怎么了?

UPD

class Post < ActiveRecord::Base
  belongs_to :user
  validates :desc, presence: true
  validates :title, presence: true, length: { maximum: 45 }
end

UPD2

class CreatePosts < ActiveRecord::Migration
  def change
    create_table :posts do |t|
      t.string :title
      t.string :desc

      t.timestamps
    end
  end
end

1 个答案:

答案 0 :(得分:4)

根据Rails惯例,模型名称应该是单数。因此,模型Post将位于文件夹app/models下,并命名为post.rb而非Posts.rb。您收到错误是因为Rails会通过约定查找名为post.rb的文件,如果找不到则会抛出错误。