Adding Joiners In One “form for”

mendel margolis
2 min readFeb 15, 2021

So you are creating a rails app, and let's say for the sake of this blog post you are creating a social media style app, where you can post something and add a tag to said post, now we want our user experience to be as pleasant as possible, therefore we don't want the user to have a separate get request to select a tag, and image id to create an image tag, we want the option to select a tag in the form to create a picture, thereby creating the picture and associated tags in one form and one post request.

Before we go into the exact syntax, let's review our model's relationships with each other.

So we have our post table, then we have our tag table with a list of tags, and then our joiner table the image tag table, now if we were to run the following code in our terminal

first = Post.firstfirst.ids 

we would get this response back

[["post_id", 18]]
=> [1, 2, 9, 10]

giving us a list of all the tag id’s associated with our picture, and the reason for this is because our post model “has_many” image tags, we can access them with a post instance, and notice how the console returns an array and that is because “id’s” plural, is telling our console that there are more than one, now what if we assign a value to our picture id’s, we would have a joiner for every tag that we assigned like so

first.tag_ids =[2,4,6]TRANSACTION (1.9ms)  commit transaction
=> [2, 4, 6]

we just destroyed our old associations and created 3 new ones.

so we know we can create tag associations through our post, let's do it in our post “form_for” to create a post tag, all we need to do is add one line here and we can select tag id’s for our post

<%=p.collection_check_boxes :tag_ids, Tag.all, :id, :name %>

let's break this code down a bit.

“p.collection_check_box” means we want the content displayed with checkboxes,

“:tag_ids” means “tag_ids” is the element we want to create for our post, and we already know we can create “tag_id’s” through creating a post,

“Tag. all” means where we are getting the data from,

“id” is what we want to take from Tag.all, we want to extract the “: id “

and “name” is how we want to display the data, we want to display the tag name

We have all the tags selected that we want but there is still one thing left, and that is we need to let the params know, that there is a new key coming in with an array value, and to assign it to our new post

params.require(:post).permit( :post_url, tag_ids:[],

and that's it folks, happy coding !!!

--

--