Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby on Rails generates model field:type - what are the options for field:type?

I'm trying to generate a new model and forget the syntax for referencing another model's ID. I'd look it up myself, but I haven't figured out, among all my Ruby on Rails documentation links, how to find the definitive source.

$ rails g model Item name:string description:text (and here either reference:product or references:product). But the better question is where or how can I look for this kind of silliness easily in the future?

Note: I've learned the hard way that if I mistype one of these options and run my migration then Ruby on Rails will totally screw up my database... and rake db:rollback is powerless against such screwups. I'm sure I'm just not understanding something, but until I do... the "detailed" information returned by rails g model still leaves me scratching...

like image 491
Meltemi Avatar asked Dec 08 '10 04:12

Meltemi


People also ask

What does Rails generate model do?

A Rails Model is a Ruby class that can add database records (think of whole rows in an Excel table), find particular data you're looking for, update that data, or remove data. These common operations are referred to by the acronym CRUD--Create, Remove, Update, Destroy.

What is a model in a Rails application?

A model is a Ruby class that is used to represent data. Additionally, models can interact with the application's database through a feature of Rails called Active Record.


2 Answers

:primary_key, :string, :text, :integer, :float, :decimal, :datetime, :timestamp, :time, :date, :binary, :boolean, :references 

See the table definitions section.

like image 191
Paul Schreiber Avatar answered Sep 29 '22 18:09

Paul Schreiber


To create a model that references another, use the Ruby on Rails model generator:

$ rails g model wheel car:references 

That produces app/models/wheel.rb:

class Wheel < ActiveRecord::Base   belongs_to :car end 

And adds the following migration:

class CreateWheels < ActiveRecord::Migration   def self.up     create_table :wheels do |t|       t.references :car        t.timestamps     end   end    def self.down     drop_table :wheels   end end 

When you run the migration, the following will end up in your db/schema.rb:

$ rake db:migrate  create_table "wheels", :force => true do |t|   t.integer  "car_id"   t.datetime "created_at"   t.datetime "updated_at" end 

As for documentation, a starting point for rails generators is Ruby on Rails: A Guide to The Rails Command Line which points you to API Documentation for more about available field types.

like image 43
Troy Avatar answered Sep 29 '22 18:09

Troy