【问题标题】:Using multiple tables in ActiveRecord在 ActiveRecord 中使用多个表
【发布时间】:2014-03-08 06:59:45
【问题描述】:

我正在尝试制作一个 api,但我只能找到使用单个表的示例。这是我发现要复制的示例之一,但需要更多表。

http://mopsled.com/2013/01/building-restful-api/

此代码还会在每次运行时创建数据库。您将如何设置它以便它只创建一次数据库。

提前致谢!

【问题讨论】:

    标签: ruby activerecord sinatra


    【解决方案1】:

    假设您有两个名为 albumstracks 的表只需要创建一次,那么您的两个请求都在这些代码行上:

    ActiveRecord::Schema.define do
      unless ActiveRecord::Base.connection.tables.include? 'albums'
        create_table :albums do |table|
          table.column :title,     :string
          table.column :performer, :string
        end
      end
    
      unless ActiveRecord::Base.connection.tables.include? 'tracks'
        create_table :tracks do |table|
          table.column :album_id,     :integer
          table.column :track_number, :integer
          table.column :title,        :string
        end
      end
    end
    

    您可以通过reading this article.获取更多信息

    【讨论】:

    • 我的回答对你有帮助吗?如果是,请点击我的答案左侧箭头下方的接受按钮接受它
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-22
    • 1970-01-01
    • 1970-01-01
    • 2020-03-18
    • 1970-01-01
    • 2013-08-18
    相关资源
    最近更新 更多