【问题标题】:Statement Invalid in Rails AdminRails Admin 中的语句无效
【发布时间】:2015-08-12 18:13:05
【问题描述】:

我正在使用rails_admin gem。当我从 localhost 打开管理面板时它工作正常,但是每当我尝试在 Rails 管理面板中显示用户时都会收到此错误。

ActiveRecord::StatementInvalid in RailsAdmin::Main#show

PG::UndefinedColumn: ERROR:  column relationships.user_id does not exist
LINE 1: ...LECT "relationships".* FROM "relationships" WHERE "relations...
                                                             ^
: SELECT "relationships".* FROM "relationships" WHERE "relationships"."user_id" = $1

我意识到这个错误可能来自我的用户模型

class User < ActiveRecord::Base
  has_many :relationships
  has_many :active_relationships, class_name:  "Relationship",
                                  foreign_key: "follower_id",
                                  dependent:   :destroy
  has_many :passive_relationships, class_name:  "Relationship",
                                   foreign_key: "followed_id",
                                   dependent:   :destroy
  has_many :following, through: :active_relationships, source: :followed
  has_many :followers, through: :passive_relationships, source: :follower
end

relationship.rb

class Relationship < ActiveRecord::Base
  belongs_to :follower, class_name: "User"
  belongs_to :followed, class_name: "User"    
end

我完全不知道为什么错误说relationship.user_id 不存在。我怎样才能解决这个问题?提前致谢。

【问题讨论】:

    标签: ruby-on-rails rails-admin


    【解决方案1】:

    这告诉您关系模型下的关系表没有user_id 列。

    当您在 User 模型中使用 has_many 关联时,您需要在关系表中有一个 user_id 列:http://guides.rubyonrails.org/association_basics.html#the-has-many-association

    检查数据库中的关系表以查看表的结构。看来您需要迁移才能将 user_id 列添加到该表。

    【讨论】:

    • 就是这样,但这并不是我真正想要的。我不想将 user_id 添加到 relationship 表中,因为它已经包含 user_ids 的 followerfollowing。有关此示例代码,请参阅我遵循的教程:railstutorial.org/book/following_users。据我了解,它应该与 user_id 没有问题。
    • 代码中引发错误的行是什么?您能否修改问题并添加该信息?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-09
    相关资源
    最近更新 更多