gpt4 book ai didi

ruby-on-rails - has_many :through looking for inexistent column

转载 作者:数据小太阳 更新时间:2023-10-29 08:31:58 39 4
gpt4 key购买 nike

我有这 3 个类:

  • 用户:

    class User < ActiveRecord::Base
    end
  • 用户故事:

    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

    结束

  • 观看的故事:

    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

最佳答案

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

关于ruby-on-rails - has_many :through looking for inexistent column,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24291937/

39 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com