DEV Community

Atomik Jaye
Atomik Jaye

Posted on

2 1

Adding table associations with Sinatra and ActiveRecord's application_controller.rb

Hi again! Today's blog post will be about adding table associations to your API endpoints!

I was working on my project, a sewing pattern database, and I ran into a problem. More like a coding organization issue. I had my models separated as such:

  • Companies (pattern makers),
  • Patterns (individual patterns and info),
  • Categories(various categories each pattern could fall under),
  • Fabrics(the type of fabrics listed on each pattern).

I had to have a fetch call for each table and it works, but I wasn't sure how to connect some tables to others. For example I asked myself "How do I access the fabrics from the pattern/fabric join table I made when I am only making a call to the patterns table?"

Well that's where this blog comes in!

My controller at the time looked something similar to this:

get "/patterns" do
    patterns = Pattern.all
    patterns.to_json
  end

  get "/categories" do
    categories = Category.all
    categories.to_json
  end

  get "/fabrics" do
    fabrics = Fabric.all
    fabrics.to_json
  end

 get "/patterns/:id" do
    pattern = Pattern.find(params[:id])
    pattern.to_json
  end
Enter fullscreen mode Exit fullscreen mode

These paths are still valid because I call them to display categories and fabrics. The only path that was giving me issues was /patterns/:id. The way my project is structured, patterns belongs_to one company and has_many categories and fabrics through their respective join tables.. in this case :pattern_categories and :pattern_fabrics. However, as you see below. I am only accessing the pattern's first level of information, and not any of my patterns associations. This gave me issues when I tried to get JSON for a single pattern.

My JSON looked like this (when accessing the /patterns/:id path)

{
id: 13,
company_id: 1,
pattern_code: "M8314",
notions: "7in zipper",
size: "XL",
yardage: 4,
extras: "Caftan-style romper and jumpsuits with sash have front opening with hook and eyes. Views B and C have opening for sash to pull through. View C has arm opening at shoulder line for a cowl drapey look and has elasticized hems.",
created_at: "2022-08-13T01:55:32.415Z",
updated_at: "2022-08-13T01:55:32.415Z",
image: "https://via.placeholder.com/150x200?text=Sewing+Pattern"
}
Enter fullscreen mode Exit fullscreen mode

As you can see, I am missing my associations. I kept thinking "Do I need to make more fetch calls? Would I need to use a for loop to join the pattern id with the category/fabric join table and somehow search through the fabric table" I was confusing myself.

HOURS LATER

I finally asked my fellow classmates for help. Initially my friend asked why I was doing so many fetch calls? I yeeted the question.. Whatchu talkin' bout Willis?... it works that's why!
But then he began to explain his process and taught me about this wonderful thing called include. How'd I missed this 7 letter word that makes my life 1000x easier?

So off to searching I went. In order to include my associations, I needed to reform my api endpoint like this:

  get "/patterns/:id" do
    pattern = Pattern.find(params[:id])
    pattern.to_json(include: [:categories, :fabrics])
  end
Enter fullscreen mode Exit fullscreen mode

I needed to 'include' my tables that are listed in my pattern.rb model. Annnd Just like ✨ magic ✨, my fetch now included all I needed for an individual pattern without all the extra code! This is how my JSON looks now:

{
id: 13,
company_id: 1,
pattern_code: "M8314",
notions: "7in zipper",
size: "XL",
yardage: 4,
extras: "Caftan-style romper and jumpsuits with sash have front opening with hook and eyes. Views B and C have opening for sash to pull through. View C has arm opening at shoulder line for a cowl drapey look and has elasticized hems.",
created_at: "2022-08-13T01:55:32.415Z",
updated_at: "2022-08-13T01:55:32.415Z",
image: "https://via.placeholder.com/150x200?text=Sewing+Pattern",
categories: [
{
id: 3,
name: "Skirts, Pants, & Jumpsuits",
created_at: "2022-08-12T03:49:55.817Z",
updated_at: "2022-08-12T03:49:55.817Z"
},
{
id: 2,
name: "Tops & Vests",
created_at: "2022-08-12T03:49:55.798Z",
updated_at: "2022-08-12T03:49:55.798Z"
}
],
fabrics: [
{
id: 5,
name: "Cotton Blends",
created_at: "2022-08-12T03:49:56.093Z",
updated_at: "2022-08-12T03:49:56.093Z"
},
{
id: 4,
name: "Cotton",
created_at: "2022-08-12T03:49:56.077Z",
updated_at: "2022-08-12T03:49:56.077Z"
}
]
}
Enter fullscreen mode Exit fullscreen mode

I hope this helps you! 😉

AWS GenAI LIVE image

Real challenges. Real solutions. Real talk.

From technical discussions to philosophical debates, AWS and AWS Partners examine the impact and evolution of gen AI.

Learn more

Top comments (0)

The Most Contextual AI Development Assistant

Pieces.app image

Our centralized storage agent works on-device, unifying various developer tools to proactively capture and enrich useful materials, streamline collaboration, and solve complex problems through a contextual understanding of your unique workflow.

👥 Ideal for solo developers, teams, and cross-company projects

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay