How to make a Seed.Rb by randomly searching Sqlite data in Rails?

Asked

Viewed 79 times

1

Since I already have a register of cities and states, which you can see below, my question is the following, how can I place within the function 10.times in the lines of address_city and address_state a parameter to search for random cities and states? within what was registered in Sqlite by 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

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,

Browser other questions tagged

You are not signed in. Login or sign up in order to post.