Creating a Model on Rails

Image Source: intertwingly.net
This is not based on a database application, so we can pretty much keep the name, which is comfortable for us. Lets take for example if we have to make a DataFile model.
C:\ruby> ruby script/generate model DataFile
- exists app/models/
- exists test/unit/
- exists test/fixtures/
- create app/models/data_file.rb
- create test/unit/data_file_test.rb
- create test/fixtures/data_files.yml
- create db/migrate
- create db/migrate/001_create_data_files.rb
Now we will create a method called save in data_file.rb model file. This method will be called by the application controller.
- class DataFile < ActiveRecord::Base
- def self.save(upload)
- name = upload['datafile'].original_filename
- directory = “public/data”
- # create the file path
- path = File.join(directory, name)
- # write the file
- File.open(path, “wb”) { |f| f.write(upload['datafile'].read) }
end