DEV Community

Cover image for Passing Private Params to an Update Method in a Controller (Rails)
Jessica Triana
Jessica Triana

Posted on • Updated on

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 “Amy’s 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 “Amy’s Bachelorette Party”.

Let’s 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 (Amy’s Bachelorette Party) in the database by the event’s 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

Top comments (0)