Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
March 6, 2020 04:03 pm GMT

Passing Private Params to an Update Method in a Controller (Rails)

In this post, I want to take a moment to dissect a block of code that I found challenging while working on my first Ruby on Rails project.

In our Bachelor/Bachelorette web app, a user can update an existing event by adding activities and other users to it.

For example, a Bachelorette named Amy can select Amys Bachelorette Party and edit it to include activities like Brunch, a day on Lake Travis, Barhopping, etc. Amy can also select each of her friends from a dropdown menu and add them to Amys Bachelorette Party.

Lets pretend that Amy wants to update her Bachelorette Party (event) to include Brunch (activity) and a friend Kelly (user)

Our Models have these relationships:

Alt Text

Our Events Controller (simplified) has this Update method with this private method:

Alt Text

Here is a line-by-line explanation of the logic in the Update method:

  1. Find the event (Amys Bachelorette Party) in the database by the events assigned ID #
  2. Find the activity to add (Brunch) from a dropdown menu within the Update Event form
  3. Find the user to add (Kelly) from a dropdown menu within the Update Event form
  4. If the event is assigned a valid activity and user, save these updates to the database UNLESS they are already saved (to prevent duplicates)
  5. If the event is successfully updated, redirect the user to a page that shows them their newly updated event with all of the event details
  6. If the event is not successfully updated(perhaps the user forgot to complete a field), then show them the original Update Event form (so they can try again)

The private method event_params dictates that, if a user is creating or updating an event, they will have access to activities and users in the database. This allows them to assign activities and users to events.

Takeaway:
After completing this project, I learned that this code could be refactored further to include checkboxes instead of dropdown menus. This would allow a user to add multiple activities and users to an event, instead of just one at a time through the dropdown menu.

Learn more about Strong Params here


Original Link: https://dev.to/jessicatriana/passing-private-params-to-an-update-method-in-a-controller-rails-3llk

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To