Skip to content

Instantly share code, notes, and snippets.

# app/models/author.rb
class Author < ActiveRecord::Base
has_many :interests
end
# app/models/interest.rb
class Interest < ActiveRecord::Base
belongs_to :author
end
@memaker
memaker / has_many_through
Last active April 7, 2017 19:30
has_many through
# using has_many :through
rails g model mountain name
rails g model climber name
rails g model adventure climber:references mountain:references
class Climber < ApplicationRecord
has_many :adventures
has_many :mountains, :through => :adventures
end
@memaker
memaker / has_and_belongs_to_many.txt
Last active April 7, 2017 18:23
Some command to set up a many to many relationship
# using has_and_belongs_to_many
rails g model mountain name
rails g model climber name
class Climber < ApplicationRecord
has_and_belongs_to_many :mountains
end
class Mountain < ApplicationRecord
$ rspec spec/models/person_spec.rb
...
Finished in 0.39298 seconds (files took 2.32 seconds to load)
4 examples, 0 failures
# spec/models/person_spec.rb
require 'rails_helper'
RSpec.describe Person, type: :model do
it "has a valid factory" do
#person = FactoryGirl.build(:person) it is also valid
expect(FactoryGirl.build(:person)).to be_valid
end
# spec/factories/people.rb
require 'faker'
FactoryGirl.define do
factory :person do
name { Faker::Name.first_name }
age { Faker::Number.between(0, 100) }
end
end
$ rake db:migrate
== 20161207175605 CreatePeople: migrating =====================================
-- create_table(:people)
-> 0.0010s
== 20161207175605 CreatePeople: migrated (0.0010s) ============================
$ rake db:test:prepare
$ rspec
...
Finished in 1.58 seconds (files took 1.64 seconds to load)
# app/models/person.rb
Person < ApplicationRecord
validates :name, presence: true
validates :age, presence: true
def identifier
[name, age].join " "
end
end
$ bundle install
Resolving dependencies...
Using rake 12.0.0
Using concurrent-ruby 1.0.2
Using i18n 0.7.0
...
(more gems here...)
...
Using web-console 3.4.0
Using rails 5.0.0.1
$ rvm list
rvm rubies
ruby-1.9.3-p484 [ x86_64 ]
ruby-2.1.0 [ x86_64 ]
ruby-2.2.0 [ x86_64 ]
ruby-2.2.2 [ x86_64 ]
=* ruby-2.3.0 [ x86_64 ]
# => - current