I am new to Rails, and so far, I have been filling model's data from the standard HTML form. What if I want to have a model called "Car" with attributes "brand", and "color" and I want to read 6 cars BUT from a text file (not an HTML form) and create 6 different car models? I have to idea where to start from. Any guidance will be very useful. Thanks
Asked
Active
Viewed 1,332 times
2 Answers
1
1) If it's for when the app is installed put Model.create statements in db/seeds.rb
2) For what are effectively model level constants, put them in classes, e.g.
class Car < ActiveRecord::Base
MODELS = %q[Ford, Honda, Buick] # %q means words, e.g. "Ford", "Honda", "Buick"
end
# Now you can use `::` to access it, e.g. Car::MODELS for the car models array.
2a) You can also create them through references, e.g.
class Car < ActiveRecord::Base
FORD = "The Ford Motor Company."
HONDA = "The international Honda Motor Company."
BUICK = "Buick Inc."
MODELS = [FORD, HONDA, BUICK]
end
# Now you can use Book::MODELS for the models array.
# and Car::FORD for the FORD type
You can edit classes at any time (this took me a bit of getting used to as I was a SQL for everything programmer for a while).
3) Files themsevlves can be easily read with
@input = File.open("/directories_to_it/file")
@input.each_line do |one_row|
CarBrand.create(:brand => one_row[0], :color => one_row[1]
end
# psuedo-code you may need to play with the line reading a bit for your columns.

Michael Durrant
- 93,410
- 97
- 333
- 497
0
JSON is a great object representational format that is easy to use and is human readable. It can handle arrays of objects as you describe. I would convert your object(s) to json and write them to a file, which you can then retrieve using JSON.parse().
see this link for an example of how to do this: How to write to a JSON file in the correct format