获取ActiveRecord :: Statement无效错误

时间:2016-01-11 06:20:25

标签: ruby-on-rails

不确定我在Rails应用程序中缺少什么。我以非常相似的方式设置了“帖子”和“项目”。但是,当我点击我的“Projects”链接时,我得到一个ActiveRecord :: Statement Invalid错误。 Posts索引页面没有这样的问题。具体来说,Projects索引页面的消息是:

“SQLite3 :: SQLException:没有这样的列:created_by:SELECT”projects“。* FROM”projects“ORDER BY created_by DESC”

我知道这通常可能是因为错误的事情 - 特别是复数与单数需要匹配。这两个型号和控制器对我来说看起来都是一样的 - 只有很小的差别。所以我找不到问题所在。

这是我的控制器页面:

class ProjectsController < ApplicationController
  before_action :find_project, only: [:show, :edit, :update, :destroy]
  before_action :authenticate_user!, except: [:index, :show]

  def index
    @projects = Project.all.order("created_by DESC")
  end

  def new
    @project = Project.new
  end

  def create
    @project = Project.new project_params

    if @project.save
      redirect_to @project, notice: "Nice work! Successfully saved!"
    else
      render 'new'
    end
  end

  def show

  end

  def edit

  end

  def update
    if @project.update project_params
      redirect_to @project, notice: "Nice work! That project was successfully updated!"
    else
      render 'edit'
    end
  end

  def destroy
    @project.destroy
    redirect_to projects_path
  end

  private

  def find_project
    @project = Project.friendly.find(params[:id])
  end

  def project_params
    params.require(:project).permit(:title, :description, :link, :slug)
  end
end

这是项目index.html.erb页面:

<h1 id="page_title">Projects</h1>

<div id="posts_wrapper" class="skinny_wrapper">
    <% @projects.each do |project| %>
        <div class="post">
            <p class="date"><%= project.created_at.strftime('%A, %B, %d') %></p>
            <h2><a href="#"><%= link_to project.title, project %></a></h2>
            <hr>
        </div>
    <% end %>
</div>

这是我的_create_projects.rb表信息:

class CreateProjects < ActiveRecord::Migration
  def change
    create_table :projects do |t|
      t.string :title
      t.text :description
      t.string :link

      t.timestamps null: false
    end
  end

我也有这个:

class AddSlugToProjects < ActiveRecord::Migration
  def change
    add_column :projects, :slug, :string
    add_index :projects, :slug, unique: true
  end
end

2 个答案:

答案 0 :(得分:3)

我认为你会发现created_by应为created_at

created_atupdated_at是您在迁移时创建的字段

t.timestamps

在您的迁移文件中。

因此,请更改您的index方法

  def index
    @projects = Project.all.order("created_at DESC")
  end

答案 1 :(得分:1)

  

SQLite3 :: SQLException:没有这样的列:created_by:SELECT&#34; projects&#34;。*   来自&#34;项目&#34; ORDER BY created_by DESC

错误清楚地表明created_by表中没有名为projects的列。

您需要生成迁移以将created_by列添加到projects表。

rails g migration add_created_by_to_projects created_by:string

然后执行rake db:migrate