Premium Content - Free Preview
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.
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?
class LikesController < ApplicationController def create product = Product.find(params[:product_id]) current_user.like(product) redirect_to :back end end
create action does a few things:
- Finds the product
- Likes the product, using the
likemethod you wrote
- redirects the visitor to a different controller action. In this case, it redirects_to
:back, which is whatever page they came from.
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: