has_many:通过寻找不存在的列

时间:2014-06-18 17:45:59

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

我有这三个班级:

  • 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

2 个答案:

答案 0 :(得分:4)

如果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

答案 1 :(得分:1)

  

PG :: UndefinedColumn:错误:列watched_stories.user_story_id确实   不存在

Rails正在寻找一个名为 user_story_id 的专栏,该专栏在 watched_stories 表中并不存在。

<强>原因

belongs_to :story, class_name: 'UserStory' 模型中有 WatchedStory 这一行,因此 class_name 指定为 UserStory ,Rails默认会查找 user_story_id

<强>修正

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

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