DnfD February 2016

Rails 4 and fields_for using seed data. How to pre-populate form?

The goal is to pre-populate the form with seed data: https://github.com/ornerymoose/GarageApp

The relevant code for iterating over stall numbers is in garages_controller.rb:

  def new
    @garage = Garage.new
    for i in 1..5 
      @garage.cars.build :stall_number => i
    end
  end

This will give 5 stall_number string values of 1, 2, 3, 4, and 5. Instead of that, how would I iterate over the values in the seeds.rb file?

Car.create(stall_number: "stall1")
Car.create(stall_number: "stall2")
Car.create(stall_number: "stall3")
Car.create(stall_number: "stall4")
Car.create(stall_number: "stall5")

So instead of the stall_numbers having values of 1, 2, 3, 4, and 5. They would have the string values listed in the seeds.rb file.

Here is the fields_for block in the garage _form.html.erb:

  <%= f.fields_for :cars do |builder| %>
      <p>Enter license for car parked in stall: <%= builder.object.stall_number %></p>
      <%= builder.label :license, "License #:" %><br />
      <%= builder.text_field :license %>
  <% end %>

Any input on the matter is greatly appreciated.

Answers


Beengie February 2016

Just do the same loop in the seed file.

for i in 1..5 
  Car.create(stall_number: "stall" + i.to_s)
end

If they are static, just create them in an array and call them.

array = ["stallA", "stallDC", "stall874", "stallNN", "stallPO", "stalSF", "stallRE", "stall456", "stall39", "stall99"]

array.each {|x| Car.create(stall_number: x)}

Post Status

Asked in February 2016
Viewed 1,254 times
Voted 12
Answered 1 times

Search




Leave an answer