【问题标题】:SQLite error on belongs_to/has_many association in Rails appRails 应用程序中的 belongs_to/has_many 关联上的 SQLite 错误
【发布时间】:2012-11-12 15:03:30
【问题描述】:

我有两个具有以下关联的模型:

  • 一个用户有很多项目。
  • 项目属于用户。

用户模型(user.rb):

 class User < ActiveRecord::Base
   has_many :projects
   attr_accessible :available, :department, :name, :skills, :title, :photo
 end

项目模型(project.rb):

class Project < ActiveRecord::Base
  belongs_to :user, :foreign_key => :user_id
  attr_accessible :project_name
end

外键迁移文件:

class AddForeignKeyToUsers < ActiveRecord::Migration
  def change
    add_column :users, :user_id, :integer
  end
end

当我致电&lt;%= @user.projects %&gt; 时,我收到以下错误消息:

SQLite3::SQLException: no such column: projects.user_id: SELECT "projects".* FROM "projects"  WHERE "projects"."user_id" = 2

【问题讨论】:

    标签: ruby-on-rails-3 sqlite associations


    【解决方案1】:

    您将外键添加到错误的表中。它应该在projects,而不是users

    class AddForeignKeyToProjects < ActiveRecord::Migration
      def change
        add_column :projects, :user_id, :integer
      end
    end
    

    由于您遵守约定,因此您不必在 Project 模型中指定外键。这应该足够了:

    belongs_to :user
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-17
      • 1970-01-01
      • 1970-01-01
      • 2015-09-11
      • 2011-04-21
      • 1970-01-01
      相关资源
      最近更新 更多