1

在重新检查代码、重新启动计算机并运行 rake db:migrate 之后,我不知道还能做什么。我不断收到以下错误:

SQLite3::SQLException: no such column: uploads.user_id: SELECT COUNT(*) FROM "uploads"  WHERE "uploads"."user_id" = 1

Extracted source (around line #12):

9:     </section>
10:   </aside>
11:   <div class="span8">
12:     <% if @user.uploads.any? %>
13:       <h3>Uploads (<%= @user.uploads.count %>)</h3>
14:       <ol class="uploads">
15:         <%= render @uploads %>

这与 has_many 关联有什么关系吗?

显示.html.erb

<% provide(:title, @user.name) %>
<div class="row">
<aside class="span4">
<section>
  <h1>
    <%= gravatar_for @user %>
    <%= @user.name %>
  </h1>
</section>
</aside>
<div class="span8">
<% if @user.uploads.any? %>
  <h3>Uploads (<%= @user.uploads.count %>)</h3>
  <ol class="uploads">
    <%= render @uploads %>
  </ol>
  <%= will_paginate @uploads %>
<% end %>
</div>
</div>

上传.rb

class Upload < ActiveRecord::Base
attr_accessible :title

belongs_to :user

validates :title, presence: true
validates :user_id, presence: true

default_scope order: 'uploads.created_at DESC'
end

用户.rb

class User < ActiveRecord::Base
attr_accessible :name, :email, :password, :password_confirmation
has_secure_password
has_many :uploads, dependent: :destroy

before_save { |user| user.email = email.downcase }
before_save :create_remember_token

validates :name, presence: true, length: { maximum: 50 }
VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
validates :email, presence:   true,
                format:     { with: VALID_EMAIL_REGEX },
                uniqueness: { case_sensitive: false }
validates :password, length: { minimum: 6 }
validates :password_confirmation, presence: true

private

def create_remember_token
  self.remember_token = SecureRandom.urlsafe_base64
end
end

来自 users_controller.rb

  def show
  @user = User.find(params[:id])
  @uploads = @user.uploads.paginate(page: params[:page])
  end

20120524145724_create_uploads.rb

class CreateUploads < ActiveRecord::Migration
def self.up
create_table :uploads do |t|
  t.string :title
  t.integer :user_id

  t.timestamps
  end
  add_index :uploads, [:user_id, :created_at]
end

def self.down
drop_table :uploads
end
end
4

2 回答 2

3

运行迁移后,如果您对其进行更新,rails 将不会重新运行它(它不知道您进行了哪些更改)。

在编辑之前回滚迁移 (rake db:rollback),或者创建一个添加额外列的新迁移。

于 2012-05-24T23:15:18.927 回答
0

迁移有时可能会失败,如果你有一些错误,例如它不会工作。确保它确实运行了,您可以检查您的 sqlite 数据库以查看是否有 user_id

于 2012-05-24T23:22:41.270 回答