Create a simple Rails project and try out what you've learned so far!
In this project you'll be creating a simple Rails project to model the
relationships between people and houses. By the end of this project, each
Person will live in a house, and each House will have an address. You will
be able to call #residents on a House instance and get a list of the
people that live in that house. You will also be able to call #house on a
Person instance and get the house where that person lives.
Pro Tip: Refer to the readings often!
- Create a new rails project using PostgreSQL.
- Remember to use the
-G,-T,--minimal, and-d=postgresqlflags when creating your project! - Remember to change
debugtobyebugand addpry-railsandannotatein your Gemfile (thenbundle install)! - Since you used the
-Gflag, Rails will not create the .gitattributes and .gitignore files. You can grab those two files from the starter repo at theDownload Projectbutton below. Copy them into the root directory of your project. - Remember to create the database!
- Remember that you need to have Postgres running in the background!
- Remember to use the
- Create a
Personmodel and apeopletable. EachPersonshould have anameand ahouse_id.- You will need to create and run a migration for each model. (Refer to the Migration reading if you need a reminder!)
- You will need to create a file called
<model_name>.rbinapp/models/for each model.Replace
<model_name>with the (singular, lowercase, snake_case) name of the model. - For each model, you should validate the presence of each attribute that the
model can have. (Refer to the Basic Validations reading for an example.)
Remember that Rails handles certain validations for you!
Hint: Run
bundle exec annotate --modelsto install a copy of the model's schema at the top of each model file.
- Create a
Housemodel and ahousestable. EachHouseshould have anaddress. Add appropriate validations.
- Create associations for
HouseandPersonsuch thatHouses can have many#residentsand eachPersonbelongs to a#house. (Refer to the readings forbelongs_toandhas_manyfor help.)- These associations rely on your specifying the correct
primary_key,foreign_key, andclass_name. Otherwise, when you call#residentson aHouseinstance, Rails will assume you are following conventions and look for aresidentstable rather than apeopletable!
- These associations rely on your specifying the correct
-
Use the
rails console--search forrails consolein the ORM Review reading to find out more about it--to create some data and run some basic queries. -
You should be able to run the following:
house = House.new(address: '308 Negra Arroyo Lane') house.save! person = Person.new(name: 'Walter White', house_id: house.id) person.save! Person.first.house # House with address: "308 Negra Arroyo Lane" House.first.residents # array containing Person with name: "Walter White"