How to make a Seed.rb by looking for random SQLite data in Rails?

1

As I already have a register of Cities and states, you can see below, my question is as follows, how can I put inside the 10.times function in the lines of address_city and address_state a parameter to search for cities and random states? within what has been registered in SQLite by the BRpopulate function.

Ruby 2.2.1 Rails 4.2.1

This is my seed.rb:

require 'faker'

#create natural_person
10.times do 
  natural_person = NaturalPerson.new(
     name: Faker::Name.name,
     short_name: Faker::Name.first_name,
     treatment: Faker::Name.prefix,
     profession: Faker::Name.title,
     email: Faker::Internet.email,
     address: Faker::Address.street_name,
     address_number: Faker::Address.building_number,
     address_district: Faker::Address.state,
     address_zipcode: Faker::Address.zip_code,
     birthday: Faker::Date.between(100.years.ago, 18.years.ago),
     phone: Faker::Number.number(10),
     mobile: Faker::Number.number(10),
     commercial_phone: Faker::Number.number(10),
     #city_id: ?
     #state_id: ?
     address_coutry: 'Brasil'
  )
  natural_person.save! 
end


    # Polpulation State and City for DB
require 'net/http'
require 'json'

  module BRPopulate
   def self.states
     http = Net::HTTP.new('raw.githubusercontent.com', 443); http.use_ssl = true
     JSON.parse http.get('/celsodantas/br_populate/master/states.json').body
  end

  def self.capital?(city, state)
    city["name"] == state["capital"]
  end

  def self.populate
     states.each do |state|
      state_obj = State.new(:acronym => state["acronym"], :name => state["name"])
      state_obj.save

  state["cities"].each do |city|
    c = City.new
    c.name = city
    c.state = state_obj
    c.capital = capital?(city, state)
    c.save
  end
end
end
end

BRPopulate.populate



Models:
NaturalPerson
State
City
    
asked by anonymous 08.06.2015 / 20:05

1 answer

0

In my case I solved it here like this:

city_id: City.order("RANDOM()").first.id,
state_id: State.order("RANDOM()").first.id,
    
10.06.2015 / 21:46