Search code examples
ruby-on-railsmany-to-manyform-forfields-for

form_for to save/delete from many_to_many connecting table


I have a catalog that has categories (think shoes, shirts, pants). The Catalog has brands assigned to it (jinco, big dog, mossimo) that will be available to the categories, but we want the ability to turn off/on a brand for a category. So in the shoes area we only want to show big dog and mossimo, in pants we want to only show jinco.

So I am in the catalog edit page, and and I am displaying each category on a table something like this:

Category   |   Jinco            |   Mossimo      |   Big Dog
Pants        |   Check-box    |   Check-box   |   Check-box
Shirt          |   Check-box    |   Check-box   |   Check-box
Shoes       |   Check-box    |   Check-box   |   Check-box

I want to create a new catalog_brand entry when the check box is selected (using AJAX remote: true) and then delete the catalog_brand entry when the check box is unselected.

Models:

catalog (has_many: catalog_brands)
catalog_brands (belongs_to: catalog, belongs_to: system_categories)
system_categories (has_many: catalog_brands)

I am on the edit action of the Catalog controller and I know I need to use a fields_for tag but I am not sure how to structure the Create and Delete actions on the catalog_brands table to make this happen. Am I over thinking it and its simple enough as the normal create/delete that is usually done?


Solution

  • If you're using a check_box, I don't think remote: true is your best bet, rather you would need to attach the an event to your checkboxes, that would fire once checked. However, if you're good with CSS or design frameworks, you could style a button/anchor tag to look like a checkbox and attach the remote: true to these, but it also brings a layer of complexity, as you would need to replace the url when it is checked. So in the end, attaching an eventlistener to your checkbox, may be the best approach. A previous SO question has a little description of how you could listen for clicks on the checkboxes

    Let me know if I was able to help or other guidance you may require.