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...
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.
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.
:primary_key, :string, :text, :integer, :float, :decimal, :datetime, :timestamp, :time, :date, :binary, :boolean, :references
See the table definitions section.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With