diff --git a/app/models/rental.rb b/app/models/rental.rb index 397b590d1..d752985c3 100644 --- a/app/models/rental.rb +++ b/app/models/rental.rb @@ -4,5 +4,5 @@ class Rental < ApplicationRecord validates :customer_id, presence: true validates :movie_id, presence: true - validates :due_date, presence: true + validates :due_date, presence: true end diff --git a/db/migrate/20171107212027_add_foreign_keys_to_rentals_model.rb b/db/migrate/20171107212027_add_foreign_keys_to_rentals_model.rb new file mode 100644 index 000000000..4006797e6 --- /dev/null +++ b/db/migrate/20171107212027_add_foreign_keys_to_rentals_model.rb @@ -0,0 +1,6 @@ +class AddForeignKeysToRentalsModel < ActiveRecord::Migration[5.1] + def change + add_foreign_key :rentals, :movies + add_foreign_key :rentals, :customers + end +end diff --git a/db/schema.rb b/db/schema.rb index 6f7142676..aaf7030fa 100644 --- a/db/schema.rb +++ b/db/schema.rb @@ -10,7 +10,7 @@ # # It's strongly recommended that you check this file into your version control system. -ActiveRecord::Schema.define(version: 20171107181648) do +ActiveRecord::Schema.define(version: 20171107212027) do # These are extensions that must be enabled in order to support this database enable_extension "plpgsql" @@ -46,4 +46,6 @@ t.boolean "checked_out" end + add_foreign_key "rentals", "customers" + add_foreign_key "rentals", "movies" end diff --git a/test/models/customer_test.rb b/test/models/customer_test.rb index a6cd4499c..714fa19af 100644 --- a/test/models/customer_test.rb +++ b/test/models/customer_test.rb @@ -3,6 +3,23 @@ describe Customer do let(:customer) { Customer.new } + describe "relationships" do + it "has a collection of rentals" do + c = Customer.new(name: "Mira") + c. save + m_id = Movie.first.id + c_id = c.id + + c.must_respond_to :rentals + c.rentals.must_be :empty? + + r = Rental.new(customer_id: "c_id", movie_id: "m_id", due_date: Date.new(2017, 12, 1)) + + c.rentals << r + c.rentals.must_include r + end # collection of rentals + end # relationships + describe "validations" do it "can be created if all fields are provided" do start_count = Customer.count diff --git a/test/models/rental_test.rb b/test/models/rental_test.rb index 4b9e9633b..715635e8a 100644 --- a/test/models/rental_test.rb +++ b/test/models/rental_test.rb @@ -23,4 +23,23 @@ Rental.count.must_equal start_count end end # validations + + describe "relationships" do + let(:m) { Movie.first } + let(:c) { Customer.first } + let(:r) { + Rental.new(customer_id: c.id, movie_id: m.id, due_date: Date.new(2017, 12, 1)) + } + it "belongs to a movie" do + r.must_respond_to :customer + r.customer.must_equal c + r.customer.id.must_equal c.id + end + + it "belongs to a customer" do + r.must_respond_to :movie + r.movie.must_equal m + r.movie.id.must_equal m.id + end + end # relationships end # Rental