DEV Community

Joe Avila
Joe Avila

Posted on

Forms and params{}

Recently I've been working with forms and Active Record a lot. I was struggling with associating an object with another, in a many to many relationship. I thought there was something wrong with my form syntax. Turns out I had a typo in my Model associations. Either way I decided to write a tutorial on how to assign multiple objects to another using collection_check_boxes.

For starter's here are my relationships. My typo was causing lots of issues, so start off by making sure your associations are correct.

class Person

has_many :pet_owners
has_many :pets, through: :pet_owners


class PetOwner

belongs_to :pet
belongs_to :owners


class Pets

has_many :pet_owners
has_many :persons, through: :pet_owners

Enter fullscreen mode Exit fullscreen mode

Once your associations are working correctly we can move on to assigning pets to their people. We'll be using a form that allows a Person to be assigned multiple dogs.

We start by building our form in views.

# /app/views/_form.html.erb
<%= form_for @person do |f| %>
   <%= f.label "First Name: " %>
   <%= f.text_field :first_name %>
   <%= f.label "Pets: " %>
   <%= f.collection_check_boxes :dog_ids, Dog.all, :id, :name %>
   <%= f.submit %>
<% end %>

# /app/controllers/persons_controller.rb
def person_params
    params.require(:person).permit(:first_name, dog_ids:[])
Enter fullscreen mode Exit fullscreen mode

A checkbox collection allows our user to select multiple dogs by checking a box, next to the dogs name. Our form will grab the dog_id assigned to that dog instance and shovel that into our array located at person_params[:dog_ids].

Once ActiveRecord see's the collection of dogs objects it will assign those dogs to the person filling out the form.

This is a super useful method for assigning multiple objects quickly. I will be using it for a project that I'm currently working on. If you have any questions, or suggestions please leave some comments.

Happy coding!

Top comments (0)