In my last post, I wrote about using Webpack with Rails and AngularJS, and how it differed from using Bower. There is definitely a bigger learning curve using Webpack, but I believe it will all be worth it when the dust settles. Besides, it seems that Bower has been deprecated. I’m going to try my hand at a tutorial using these three technologies and share my confusion as we go. ES6 syntax will be used in Angular also, which changes how we write our components. Let’s dig in.

The Setup

I’ll assume that you have Rails installed already. We’re going to build a simple CRUD app using Rails as an API on the back end, and AngularJS on the front end and Webpack to bridge the two. We’re going to build a Meals app, with a users table and a meals table. It’s simple but what we want out of this is to be able to use these technologies together – then we can start adding complexities.

‘cd’ into you directory of choice and start a new rails app:

rails new meals --skip-turbolinks

We’re skipping turbolinks because it can cause trouble with Angular. Now that the basic Rails skeleton is created, ‘cd’ into ‘meals’ and open Atom (or your text editor of choice). The version of Rails I’m using is 5.0.6. I’m using the built-in database – sqlite3 – because using Postgres would be adding another complexity to this that we don’t need. Let’s make our first commit to github. I’ll assume you know how to start a repo.

git add .
git ci -m 'initial commit'
git remote add origin https://github.com/SiamKing/meals.git
git push -u origin master

Now let’s create our models. I usually don’t use ‘scaffold’ to generate my models because it adds so much bloat to Rails, but I’m going to use it because it’s so easy – that’s what we’re going for.

rails g scaffold user name:string
rails g scaffold meal title:string
rails g model user_meal user_id:integer meal_id:integer
rails db:migrate

Like I said – super basic. Now that the databases are created, let’s enter the rails console in the terminal and create our first user and meal.

rails c

User.create(name: 'Allison')
Meal.create(title: 'Pizza')

As long as we migrated our database, these commands should work, which means we’ll have our first user and meal. Now we have to think about the association between these two tables. Well, users have many meals and meals have many users. So, it’s a has many to has many relationship. Let’s go into our models and add the associations.

class User < ApplicationRecord
  has_many :user_meals
  has_many :meals, through: :user_meals
end

class Meal < ApplicationRecord
  has_many :user_meals
  has_many :users, through: :user_meals
end

class UserMeal < ApplicationRecord
  belongs_to :user
  belongs_to :meal
end

Let’s try to add a meal to our first user…

rails c

UserMeal.create(user_id: 1, meal_id: 1)
# created an association in our joins table for the first user and first meal

User.first.meals
# Now we can see the first users meals
=> #<ActiveRecord::Associations::CollectionProxy [#<Meal id: 1, title: "Pizza", created_at: "2017-09-17 22:51:13", updated_at: "2017-09-17 22:51:13">]>

Alright! Our models are working as they should, so the next step is to serialize our models into an API so they can be consumed by our front end. We’ll use the wonderful Active Model Serializers for this. Of course there’s a gem! Add this line to your gem file:

gem 'active_model_serializers', '~> 0.10.0'
bundle install

Now let’s create our serializers.

rails g serializer user
rails g serializer meal
rails g serializer user_meal

This generated serializers for our three models. Let’s add our associations.

class UserSerializer < ActiveModel::Serializer
  attributes :id, :name
  has_many :user_meals
  has_many :meals, through: :user_meals
end

class MealSerializer < ActiveModel::Serializer
  attributes :id, :title
  has_many :user_meals
  has_many :users, through: :user_meals
end

class UserMealSerializer < ActiveModel::Serializer
  attributes :id
  belongs_to :user
  belongs_to :meal
end

Now we have our associations set up. Let’s run our local server and see what we have. Run ‘rails s’ in your terminal and go to ‘http://localhost:3000/users/1.json&#8217; in your browser. This should give us our first users information in JSON format. It should look something like this:

{
id: 1,
name: "Allison",
created_at: "2017-09-17T22:50:16.012Z",
updated_at: "2017-09-17T22:50:16.012Z",
url: "http://localhost:3000/users/1.json"
}

Ok that’s cool, we have some JSON! The only thing is we can’t see our user’s meals. Let’s fix that! Open up your users controller and add this to you show method:

if @user
  render json: @user, include: { meals: [:title] }
end

Now refresh your browser and voila!

{
  id: 1,
  name: "Allison",
  meals: [
 {
    id: 1,
    title: "Pizza"
  }
  ]
}

Sweet! We can see our associations! Our back end is fully functional and is set up as an API. This JSON formatted information can now be consumed by our front end. This concludes the first part of this series. I’ll be back next week for part 2. We’ll get our hands really dirty setting up Webpack and Angular. Until then…Cheers:)

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s