Brendan E
Brendan E

Reputation: 11

How to use Faker in my Rails controller to make a random set of data?

def create
  climates = ["beachy", "very cold", "dry", "tundra", "rain forest", "north pole"]

  destination = Destination.create {{name: Faker::Name.last_name + " Island", climate: climates.sample}}

  redirect_to destinations_path
end

I want to have both an option for a user to create new data via their inputs, but I also want there to be an option for them to click "Random Destination" button and it will add Faker data.

Right now, this creates a new row in my Database, but it doesn't input the data.

using Postgres Db and ActiveRecord, for what it's worth.

Upvotes: 0

Views: 1172

Answers (2)

Rodrigo Martinez
Rodrigo Martinez

Reputation: 711

Haven't you tried using normal parenthesis instead of hash parenthesis?, as in:

destination = Destination.create ({name: Faker::Name.last_name + " Island", climate: climates.sample})

Maybe that's why no attribute was being saved on database, create expects a hash of attributes, not a hash of hashes of attributes.

Upvotes: 1

Ben Hawker
Ben Hawker

Reputation: 949

This could be completely wrong but my approach previously was to make use of FactoryGirl combined with Faker to achieve this. It wasn't obvious without making use of FactoryGirl. It does however have the nasty side effect of loading FactoryGirl with your other env's with my not be ideal. My approach was:

Make sure faker and factory_girl gems are included in development/production groups

gem 'faker', '~> version'
gem 'factory_girl', '~> version'

In the FactoryGirl initializer you may need to specify the env's in which you will allow it's use.

allowed_envs = %(development staging)

if allowed_envs.include?(Rails.env)
 FactoryGirl.find_definitions
end

Then in your controller, build/create your destination.

fake_destination = FactoryGirl.build(:destination)

which will user Faker, so from (factories/destination.rb):

name { Faker::Name.last_name }

and then use the relevant attribute in your object creation.


This may well be a long solution to a much simpler problem however!

Upvotes: 0

Related Questions