简体   繁体   中英

How to use Faker gem without a model in Ruby On Rails?

First time posting here. I currently have a Ruby on Rails project in which I have a PostgreSQL database. I recently created a table in the PostgreSQL database and I wanted to generate fake data to populate it. The problem is that the way I usually do it is by using the model, which I don't have for my table in my PostgreSQL database. I'd usually do something like:

50.times do
  Model.create({ ...properties })
end

How would I go about it if I don't have the model? Is it possible to do it with the table name? If I just use the table name (which doesn't have a model), I get this error: NameError: uninitialized constant .

Any help is appreciated :)

aburr answered my question perfectly!

My first thought if you do not have a model or class of any kind associated with the SQL table then you may be able to execute a SQL insert statement.

maybe something like this

require 'pg'
require 'faker'

db =  PG.connect({:dbname => 'my_db_name'})

50.times do
  db.exec("insert into Users (name) values(#{Faker::Name.name}")
end

Here is the Faker Readmehttps://github.com/faker-ruby/faker/blob/master/README.md#usage

and a reference for using SQL with Ruby http://zetcode.com/db/postgresqlruby/

I'd recommend making a model for the table. It's trivial. If you're on Rails 6, you can make use of insert_all to do the creation significantly faster.

class SomeThing < ApplicationRecord
end

If you want to forego that, you can use exec_insert to perform the insert manually.

ActiveRecord::Base.connection.exec_insert(
  'insert into some_thing (first_name, last_name) values ($1, $2)',
  nil,
  [[nil, Faker::Name.first_name], [nil, Faker::Name.last_name]]
);

Finally, rather than writing 50.times { SomeThing.create(...) } manually, consider using FactoryBot .

factory :some_thing do
  name { Faker::Name.name }
end

FactoryBot.create_list(:some_thing, 50)

The problem isn't about gem 'faker', actually it's a fake data generator. So the problem is about ActiveRecord, you need to find out the docs about ActiveRecord .
Typically, Model.create(foo: 'bar') means insert into Model (foo) values('bar') .
So ActiveRecord has raw sql operations in case you have some more complicated scenarios ActiveRecord::Base.connection.execute(sql) .
If you have any chance to use the gem sequel , you will get more understanding behind the scene.

  • Database (MySQL, PG)
  • Database connector (mysql2, pg)
  • ORM (ActiveRecord, Sequel)

That's all you need to handle the database.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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