ga-wdi-exercises / project2

[project]
1 stars 30 forks source link

Add tags on bowl create vs. new form? #907

Closed lizardbird closed 7 years ago

lizardbird commented 7 years ago

I now have a bowls model, a toppings model, and a topping_tag join table between the two. I can add toppings to my bowls and show all bowls that have that topping. Yay! But, is there a way to add topping_tags to the new/edit bowl form so a user can tag it when creating/editing a bowl vs. clicking through afterwards and adding tags?

When I am trying to do it, I get an error that the bowl (needed to associate the tags) does not exist yet, which makes sense since it has not technically been created yet. First argument in form cannot contain nil or be empty

I plan to get in the office hours queue to discuss in the morning, but if there is good reading on this somewhere, please send my way! Googling thus far has not yielded a relevant result other than https://stackoverflow.com/questions/2050133/adding-tags-to-posts-in-ruby-on-rails, which is not really a solution. Thx in advance!

lizardbird commented 7 years ago

Or should I just abandon the concept of doing it as a many to many relationship and instead just use this gem? :)

https://github.com/mbleigh/acts-as-taggable-on

juancgarcia commented 7 years ago

I've found a solution for you based on this tutorial

We'll take advantage of the form helper method collection_check_boxes

Within your bowl form view (/app/views/bowls/_form.html.erb), inside of the form_for block, add this line:

<%= f.collection_check_boxes :topping_ids, Topping.all, :id, :name %>

And remove the following:

  <%= form_for [@bowl, @topping_tag] do |f| %>
  <%= text_field_topping_tag :topping_name %>
  <%= f.submit "Add Toppings" %>
  <% end %>

This will generate a group of checkboxes, one per Topping which will be pre-checked based on the join table entries for the current Bowl (or all unchecked on a new bowl)

Then in app/controllers/bowls_controller.rb in order to get these ToppingTags added/deleted to our Bowl, we modify the strong params method, to permit the array field topping_ids:

def bowl_params
  params.require(:bowl).permit(:price, :broth, :noodle, :protein, :is_veg, :title, :review, :img_url, :restaurant_id, topping_ids:[])
end

That's it. Now your Topping selections on the form will add or remove ToppingTag entries based on the checkboxes.

Try that out and let me know if you run into any snags.

lizardbird commented 7 years ago

Thanks Juan! I've decided to change where this feature is on the site for now, but I'm definitely saving this for the future. Cheers!