Today I have finally completed my rails project and while it isn’t really that pretty to look at, there is quite a lot of things going on in the back.
My rails project is more or less and updated version of my Sinatra app. The idea was that it would be a site where users could post their pets and if they were for adoption, other users could adopt the pets. I suppose it has no use in the real world, I am absolutely terrible at thinking of great ideas. But I needed to do something to demonstrate my ability to create a full CRUD rails application.
The hardest part in creating my application was creating the original form. After having redone the entire sinatra section on learn as well as the rails section I felt I had a pretty good grasp on how nested forms work but despite this, I struggled for days trying get my form set up properly. With my original associations a User has many Pets. Breed has many pets and user has many breeds through pets. So user and breeds had a many to many relationship with Pets acting as a join table.
I tried creating a form for new pets and assigning a breed as a nested attribute. The collection select box refused to work!! Unfortunately all research has concluded that accepts_nested_attributes will not work on the join table model. So Instead I tried creating my own attributes method. Following Avi’s lectures and using build_breed instead of build. Collection select still refused to work, though my methods worked in the rails console.
So after fussing for a week, I decided to change my association. Now I have a new join table called PetBreeds. Which forms a many to many relationship between Pet and Breeds. Also apparently I have discovered that User can still have many Breeds through pets as well as vice versa even though the association is now in a sense further apart.
With these associations in place I went back once again to tackle my form. Everything mostly worked except for the fact that my collection select wasn’t working properly. So I switched to checkboxes. That worked fine! What gives? They use the same exact format aside from method name.
Well it turns out, I was passing a normal symbol called breed_id into my strong params hash. Collection select expects an array breed_id
That took about another week to discover and fix. That 1 small thing.
Given how close I was to solving my original problem with my original associations. I probably would have had it working if it weren’t for that last part. I could have probably had this done in 3 days. The problem that I had with my form the entire time was the fact that my collection select wouldn’t work no matter how many ways I rewrote it and in the end it was a pair of brackets.
Oh, and in the end I went with check boxes.
I love programming.
But I would be lying if I didn’t say it is a pain in the ass.