DEV Community

jss475
jss475

Posted on

Creating Custom Methods in Rails

I wanted to cover making custom methods in rails today. Rails is quite the powerful tool and can accomplish a lot of the actions you may want to do on the front end.

Let's go over an example that I've worked on:

I have three tables.

  1. User
  2. Restaurant
  3. UserRestaurant - the joiner table for User and restaurant

The UserRestaurant table belongs to both the user and restaurant. It also holds the following information:

  1. upvoted? (boolean)
  2. downvoted? (boolean)
  3. Review (string)

So, when a user leaves an upvote, downvote and/or review on a restaurant it's handled by the UserRestaurant table.

Now, when a user upvotes a restaurant, a UserRestaurant instance is created and the upvoted? attribute is set to true on the backend. However, what happens when this same user wants to leave a review on the same restaurant? You have to first find the original instance and then update it. You can do this on the frontend by using filters and what not or you can accomplish the same on the backend. Or what if the user leaves a review first and then upvotes? You'll have to create a UserRestaurant instance with a review and then update the upvoted? attribute.

This is where creating a custom method can help.

Here's a bit of code I wrote to accomplish let's say making an upvote first.

def create_update
        # I'm just taking the params that were sent with the post request here and setting them with different variable names 
        #ur_params here permit the following attributes: user_id, restaurant_id, upvoted?, downvoted?, and review
        user_id =ur_params[:user_id]
        restaurant_id = ur_params[:restaurant_id]

        # I then check to see if this instance exists
        ur_found = UserRestaurant.find_by user_id: user_id, restaurant_id: restaurant_id

        # If the UserRestaurant exists for this specific pair, just update it
        if ur_found
            ur_instance = ur_w_all
            ur_instance.update(ur_params)
        # If the UserRestaurant doesn't exist, create it!
        else
            ur_instance = UserRestaurant.create(ur_params)
        end
        render json: ur_instance, status: :created
end
Enter fullscreen mode Exit fullscreen mode

By using this custom method, it can handle both an update and create when necessary!

Happy coding!

Top comments (0)