【问题标题】:has_many :through looking for inexistent columnhas_many :通过寻找不存在的列
【发布时间】:2014-08-09 03:01:27
【问题描述】:

我有这 3 个课程:

  • User:

    class User < ActiveRecord::Base
    end
    
  • UserStory:

    class UserStory < ActiveRecord::Base
      belongs_to :owner, class_name: 'User'
      belongs_to :assigned, class_name: 'User'
      belongs_to :board
    
      has_many :comments
      has_many :watched_stories
      has_many :watchers, through: :watched_stories, source: :user
    

    结束

  • WatchedStory:

    class WatchedStory < ActiveRecord::Base
      belongs_to :user
      belongs_to :story, class_name: 'UserStory'
    end
    

当我尝试通过UserStory#watchers 列出所有观察者时,我看到了这个错误:

PG::UndefinedColumn: ERROR:  column watched_stories.user_story_id does not exist

似乎关系has_many through 是错误的,但我可以看到错误。我在这里想念什么?

我的迁移:

class CreateWatchedStories < ActiveRecord::Migration
  def change
    create_table :watched_stories do |t|
      t.references :user, index: true
      t.references :story, index: true, references: :user_story

      t.timestamps
    end
  end
end

【问题讨论】:

  • 同样的事情:ActiveRecord::StatementInvalid: PG::UndefinedColumn: ERROR: column watched_stories.user_story_id does not exist
  • 嗯..因为你没有在migration中定义它..这是我们经常犯的错误......
  • 它正在watched_stories 表中寻找一个名为user_story_id 的键,但找不到它。您用于将 WatchedStory 连接到 UserStory 的外键名称是什么?
  • @ArupRakshit 那么我应该怎么做呢?
  • @Sharagoz 它是story_id

标签: ruby-on-rails ruby ruby-on-rails-4 has-many-through


【解决方案1】:

如果WatchedStoryUserStory 通过story_id 连接,则需要指定,否则Rails 将假定它是user_story_id

class WatchedStory < ActiveRecord::Base
  belongs_to :story, class_name: 'UserStory', foreign_key: :story_id
end

class UserStory < ActiveRecord::Base
  has_many :watched_stories, foreign_key: :story_id
end

【讨论】:

    【解决方案2】:

    PG::UndefinedColumn: ERROR: column seen_stories.user_story_id 确实 不存在

    Rails 正在查找名为 user_story_id 的列,该列在您的 watched_stories 表中不存在。

    原因

    您在 WatchedStory 模型中有这条线 belongs_to :story, class_name: 'UserStory',因此将 class_name 指定为 UserStory ,Rails 默认会查找 user_story_id

    修复

    可以通过在您的 WatchedStory 模型中设置 foreign_key 选项来解决该错误

    class WatchedStory < ActiveRecord::Base
      belongs_to :user
      belongs_to :story, class_name: 'UserStory',foreign_key: :story_id
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-11-24
      • 1970-01-01
      • 2020-03-16
      • 2021-04-23
      • 1970-01-01
      • 1970-01-01
      • 2013-11-24
      相关资源
      最近更新 更多