bin/rails generate controller Articles index [--skip-routes]
bin/rails generate model Article title:string body:text
Model names are singular, because an instantiated model represents a single data record. To help remember this convention, think of how you would call the model's constructor: we want to write
Article.new(...)
,not Articles.new(...)
. source
bin/rails db:migrate
bin/rails console
#Play with entity
entity = EntityClass.new(propertyOne: "value")
entity.save
entity
EntityClass.find(1)
EntityClass.all
EntityClass.all
#db/seeds.rb
# frozen_string_literal: true
EntityClass.destroy_all
EntityClass.create!(
[
{ name: 'Foo' },
{ name: 'Bar' }
]
)
puts "Created #{EntityClass.count} entities"
rails db:seed
If you don't need to do anything with the relationship model, it may be simpler to set up a has_and_belongs_to_many relationship (though you'll need to remember to create the joining table in the database). source
# models
# /!\ Do no forget plural
class Foo < ApplicationRecord
has_and_belongs_to_many :bars
end
class Bar < ApplicationRecord
has_and_belongs_to_many :foos
end
class SweetNameForMigration < ActiveRecord::Migration[7.0]
def change
# if needed
create_table :foo do |t|
# declare columns
end
# if needed
create_table :bar do |t|
# declare columns
end
create_table :modelas_modelbs, id: false do |t|
t.belongs_to :foo
t.belongs_to :bar
end
end
end
# Get entities for each associtation
foo = Foo.create({})
bar = Bar.create({})
bar.foos << foo
# or
foo.bars << bar
render json: foo, include: :bar
bin/rails dbconsole
-- Play with database
SELECT * FROM table;
Show all routes
bin/rails routes
Filter routes by controller
rails routes -c[--controller]=controller_name
Show all commands
rails -T
Show all commands with a filter
rails -T test