Like Button


Premium Content - Free Preview

forms

Forms are an essential part of dynamic web applications, since they let users make actual changes to the database. Previously we used a gem to generate admin forms, but now we're going to let ordinary users make changes. This means we need to make sure that the user is who they claim to be, but luckily Rails helps take care of that for us.

Our form will actually just be a simple button to let users like specific products. Later, you can learn more about the different kinds of form helpers Rails provides.

like action

Let's create a button for liking products. What controller and action should we use for liking products?

When a user likes a product, a like record is created. To follow standard Rails practice, we should use a likes_controller with a method create in it which will be used for liking products. Go ahead and generate the likes controller:

rails generate controller Likes

Now we need to create a create route:

resources :likes, only: :create

This creates a standard create route. We're going to pass the create action a parameter :product_id for the id of the product to like. Can you setup the create action so it likes the specified product?

create like code

like button

Now that the controller is all set up, we can create the like button form. Rails provides helpers to make it easier to generate the HTML for forms and make them secure. As shown in the Rails Form Guide, the simplest form consists of the following:


End of Free Content Preview. Please Sign in or Sign up to buy premium content.

Contact Us
Sign in or email us at [email protected]