【问题标题】:Rails console database schema checkingRails 控制台数据库模式检查
【发布时间】:2014-09-12 21:28:03
【问题描述】:

我是 rails/ruby 新手,我想知道如何仔细检查我的数据库架构是否正确构建在 rails 控制台中

rails c

ActiveRecord::Base.connection.tables 给了我

的输出
["schema_migrations", "users", "expense_pictures", "income_pictures", "income_texts", "expense_texts"] 

如何在控制台中检查我是否正确构建了以下架构?

从用户到 IncomePictures 和 ExpensePictures 是外键。 IncomePictures 到 ExpensePictures 也是相应文本的外键

这是我的模型:

class ExpensePicture < ActiveRecord::Base

  belongs_to :user
  mount_uploader :image, ImageUploader
  has_one :expense_text
end

class ExpenseText < ActiveRecord::Base
  belongs_to :expense_pictures
end

class IncomePicture < ActiveRecord::Base
  belongs_to :user
  mount_uploader :image, ImageUploader
  has_one :income_text
end

class IncomeText < ActiveRecord::Base
  belongs_to :income_pictures
end

class User < ActiveRecord::Base
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :rememberable, :validatable

  has_many :expense_pictures 
  has_many :income_pictures

end

【问题讨论】:

    标签: ruby-on-rails ruby database-schema


    【解决方案1】:

    您可以在db/schema.rb 文件中查看此内容。如果您不确定,您可以之前运行 bundle exec rake db:schema:dump - 此 rake 任务从数据库重新创建 schema.rb 文件。

    根据您编辑的问题,您应该生成以下迁移:

    bundle exec rails g migration add_user_id_to_expense_pictures user:references
    bundle exec rails g migration add_expense_picture_id_to_expense_texts expense_picture:references
    bundle exec rails g migration add_user_id_to_income_pictures user:references
    bundle exec rails g migration add_income_picture_id_to_income_texts income_picture:references
    

    并使用bundle exec rake db:migrate 运行它们。

    另外,您的某些关联设置不正确。应该是:

    class ExpenseText < ActiveRecord::Base
      belongs_to :expense_picture
    end
    

    class IncomeText < ActiveRecord::Base
      belongs_to :income_picture
    end
    

    【讨论】:

    • 我很新,我对所有迁移和 rake 迁移执行的魔力感到有点迷茫。我目前有这个。我觉得我好像错过了什么dpaste.com/2TKPYPK
    • @Liondancer,所以您当前的数据库架构不是您所期望的?
    • 嗯,我只是不确定是否建立了外键连接
    • 为什么要建立外键连接?默认情况下,Rails 不会生成它们。
    • 我是 Rails 新手,所以我不知道。我认为 has_many 和 belongs_to 成功了
    【解决方案2】:

    ActiveRecord::Base.connection.schema_search_path 命令将帮助您了解当前架构

    【讨论】:

      【解决方案3】:

      我认为您可以通过this link 中列出的一些工具来可视化 Rails schema.rb

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-06-17
        • 2017-02-23
        • 1970-01-01
        • 1970-01-01
        • 2011-07-21
        相关资源
        最近更新 更多