Outline
If you're not familiar with what ActiveRecord is read this Rails guide.
Rails ships with generators that help us create ActiveRecord migrations and
models quickly. Let's start generating our models. We can do this by using the
rails generate model
, and then specifying the name of the model, followed by
field
:type
for each of our fields in our model.
rails generate model Post title:string link:string upvotes:integer
rails generate model Comment body:string upvotes:integer post:references
Each of these commands will generate a migration we can run to create the table
in our database, along with an empty model and test files for us. notice
even though we stated post:references
while generating comments, this only
creates the post_id
column and index in generated migrations. We'll still
need to run rake db:migrate
and declare an association in posts.rb
to make
our models aware of the association.
rake db:migrate
has_many
association in app/models/post.rb
class Post < ActiveRecord::Base
has_many :comments
end
Post
model, let's also override the as_json
method so that all json representations of our posts will include the comments.
class Post < ActiveRecord::Base
has_many :comments
def as_json(options = {})
super(options.merge(include: :comments))
end
end
Using as_json
is a simple way to change the json output of our models
throughout our application, but can get complex over time as you your app
grows. If you want to separate your view logic out of your models completely,
you can look into a using a templating engine for json such as jbuilder
which ships with Rails 4 by default or rabl-rails.
Now we should have all of our models created and ready to be used with the rest of our project.