Easily create and edit associations in a middle table 【Ruby on Rails】

Tomoharu Tsutsumi
2 min readMar 29, 2021

--

When I was writing codes of my company’s application, I faced this problem. First of all, I’m going to show you the structure of the tables.

The structure of the tables in our project

The chart is below.

Specification

A user can create a new task with multiple chosen labels. Therefore, when the new task is created, multiple records of the labelling table are done as well. For example, the label table would have records like ‘bug’(id is 1), ‘immediately’(id is 2), and ‘not now’(id is 3). If I were the user and chose ‘bug’ and ‘not now’, records of the labelling table would be created like this.

id: 1, task_id: 1, label_id: 1
id: 2, task_id, 1, label_id: 3

How to write codes

Controller would be like this.

  def create
@task = Task.new(task_params)
if @task.save
redirect_to root_path
else
render :new
end
end


private

def task_params
params.require(:task).permit(:name, label_ids: [])
end

Models would be like this.

class Task < ApplicationRecord
has_many :labellings, dependent: :destroy
has_many :labels, through: :labelings
end
class Labelling < ApplicationRecord
belongs_to :task
belongs_to :label
end
class Label < ApplicationRecord
has_many :labellings, dependent: :destroy
end

You can create the task with multiple labels.

How about editing?

What if the user want to edit the labellings? For example, if the user want to delete two labels(‘bug’ and ‘not now’) and attach ‘immediately’, does this code can deal with it? The answer is ‘of course, rails will do it automatically!’ You don’t need to develop a ‘delete_all’ method. Rails will automatically delete records user removed at the check boxes.

My LinkedIn account. Please contact me!

https://www.linkedin.com/in/tomoharu-tsutsumi-56051a126/

--

--

Tomoharu Tsutsumi

Senior Software Engineer at two industry-leading startups ( Go | Ruby | TypeScript | JavaScript | Gin | Echo | Rails | React | Redux | Next)