Thatdude1
Thatdude1

Reputation: 903

How to random generated data into my table - Ruby on Rails

Say I have table with the following columns:

class CreatePosts < ActiveRecord::Migration
  def change
    drop_table :posts

    create_table :posts do |t|
      t.string :First_Name
      t.string :Last_Name
      t.string :Company

      t.timestamps
    end
  end
end

I've been lookin up gems such as faker, Randexp, foregery. But how exactly will the data be imported into the database, So far I've only played around things that go into the database via a form.

I'm assuming it is done through the controller:

def create
  @post = Post.new(post_params)

  @post.save
  redirect_to @post
  end

But not sure how exactly, any examples or hints to guide me through this? Thanks

Upvotes: 1

Views: 1417

Answers (2)

Helios de Guerra
Helios de Guerra

Reputation: 3475

It really depends on what you're trying to do:

If you just want to populate the db with data for testing, you could use seeds.

Or, you could create a rake task to do this, e.g.

Best way to fill development db in rails

Or create a model to create the data which you could call from the console, e.g. using the 'ffaker' gem...

class RandomPost
  attr_reader :first_name, :last_name, :company

  def initialize options = {}
    @first_name = options[:first_name] ||= Faker::Name.first_name
    @last_name = options[:last_name] ||= Faker::Name.last_name
    @company = options[:company] ||= Faker::Company.name
  end

  def save
    Post.create({first_name: @first_name, last_name: @last_name, company: @company})
  end

end

Then if you need to create multiple random posts in the console you could do...

10.times do
  post = RandomPost.new
  post.save
end

Upvotes: 0

Jasdeep Singh
Jasdeep Singh

Reputation: 3326

If this is something that you need to bootstrap your application with, you can either use the seeds file or a rake task which are pretty much the same thing.

Only reason I can think of why you would use Faker for this is if you want to populate your Db for some testing, is that true? If yes, then the approach might vary a little.

  1. Using seeds file:

Open db/seeds.rb file and just use active record methods to start populating data.

Post.create!(First_Name: 'Name', Last_Name: 'Last', Company: 'Company Name')

Once you've written your expected code, just run rake db:seed to populate the db.

Upvotes: 2

Related Questions