简体   繁体   English

Rails和Heroku:如何将记录添加到数据库?

[英]Rails and Heroku: How to add records to database?

I am new rails. 我是新手。 I've developed a new app which shows image logos and my database contain url for these images- 我已经开发了一个新的应用程序,该应用程序显示图像徽标,并且我的数据库包含这些图像的网址-

In my local development environment I've added records into the database manually. 在本地开发环境中,我已将记录手动添加到数据库中。 My migration file for creation table looks like as follows- 我的用于创建表的迁移文件如下所示:

class CreateBooks < ActiveRecord::Migration[5.0]
  def change
    create_table :books do |t|
      t.string :title
      t.string :author
      t.string :category
      t.text :description
      t.text :logo_url
      t.string :pdf_file_url

      t.timestamps
    end
  end

Controller- 控制器-

def get_all_books
  # @books = Book.find(2);
  @books = Book.where(:id => 1..3)
  logger.debug(@books.inspect)
  render :json => @books
end

My question is there any other way to add records to my books table? 我的问题是还有其他方法可以将记录添加到book表中吗?

And when I deploy my app to heroku how to add these records to heroku also? 当我将应用程序部署到heroku时,如何将这些记录也添加到heroku?

You can create a migration file to add columns to your table, for instance if you want to add the amount of pages to the book as integer you can do this: 您可以创建一个迁移文件以向表中添加列,例如,如果您想将书的页数作为整数添加,可以执行以下操作:

rails generate migration AddPagesToBooks pages:integer

and then run rake db:migrate or rails db:migrate (on rails 5+) 然后运行rake db:migraterails db:migrate (在Rails 5+上)

And to add them to your Heroku application you can use heroku run rake db:migrate 并将它们添加到您的Heroku应用程序中,您可以使用heroku run rake db:migrate

EDIT 编辑

If you want to add records to your database you can use your db/seeds.rb file 如果要将记录添加到数据库,则可以使用db/seeds.rb文件

In there you can do something like this: 您可以在其中执行以下操作:

100.times do |i|
  Book.create!(title: "book ##{i}", author: "Author ##{i}.",
              category: "category ##{i}", description: "description ##{i}",          
              logo_url: "/logo/logo##{i}", pdf_file_url: "/pdf/file##{i}")

And then run rails db:seed or rake db:seed 然后运行rails db:seedrake db:seed

This will create 100 records of book with ##{i} being numbers 1-100. 这将创建100条记录,其中##{i}是数字1-100。

You can also check this video to get a better understanding. 您也可以查看视频,以更好地理解。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM