【问题标题】:Rails: Multiple references to the same model errorRails:多次引用同一模型错误
【发布时间】:2015-10-16 15:08:27
【问题描述】:

我有一个 Message 模型,它有一个 user 和一个 teammember(两者都是用户)。 这些模型是:

# message.rb
class Message < ActiveRecord::Base
  belongs_to :user
  belongs_to :teammember, :class_name => "User", :foreign_key => 'teammember_id' 
end

# user.rb
class User < ActiveRecord::Base
  has_many :messages
end

我有这个迁移:

class CreateMessages < ActiveRecord::Migration
  def change
    create_table :messages do |t|
      t.references :user, index: true, foreign_key: true
      t.references :teammember, index: true, foreign_key: true
      t.text :body
      t.boolean :read, default: false

      t.timestamps null: false
    end
  end
end

当我在本地(使用 sqlite3)运行 rake db:migrate 时,一切正常。 问题是当我部署到heroku(使用postgresql)并运行

heroku run rake db:migrate

它引发下一个错误:

PG::UndefinedTable: 错误: 关系“团队成员”不存在 :ALTER TABLE“消息”添加约束“fk_rails_7efc67ccc9” 外键(“teammember_id”) 参考“团队成员”(“id”)

您知道问题出在哪里,我该如何解决?

【问题讨论】:

    标签: ruby-on-rails ruby postgresql heroku


    【解决方案1】:

    Rails 根据关联进行猜测,因为您引用的表无法从关联中确定,您必须自己添加。

    class CreateMessages < ActiveRecord::Migration
      def change
        create_table :messages do |t|
          t.references :user, index: true, foreign_key: true
          t.references :teammember, index: true
          t.text :body
          t.boolean :read, default: false
    
          t.timestamps null: false
        end
        add_foreign_key :messages, :users, column: :teammember_id
      end
    end
    

    【讨论】:

    • 作为答案的补充,运行sqlite的OP本地机器没有任何抱怨,因为rails sqlite适配器不支持foreign_key(所以完全忽略了有问题的部分),只有mysql和pg适配器做edgeguides.rubyonrails.org/…
    猜你喜欢
    • 2011-01-04
    • 2013-08-12
    • 2011-09-19
    • 2021-08-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多