[Ruby] Use the for statement to implement the Hoshigo function

1 minute read

1. Prepare the column

Here’s how to implement a 5 star rating for your store and food posts! !! First, prepare a column to store the number of stars. Create an integer column named star.

rails g migration AddStarToPosts star:integer

The migration file is as follows.

class AddStarToPosts <ActiveRecord::Migration[5.1]
  def change
    add_column :posts, :star, :integer

I will migrate.

rails db:migrate

Check the schema of db and put it in the posts table


t.integer "star"

It is OK if it is written!

2. edit new page

If there are 2 stars, we will send “2”, and if there are 5 stars, we will send “5”. Anything is acceptable as long as you can send a numerical value, but here we will implement it with radio


<%= form_for @posts do |f| %>
  <div class="field">
    <%= f.label :name %>
    <%= f.text_field :name %>
<-! Added part ->
   5 stars:
    <label><%= f.radio_button :star, 1 %> 1</label>
    <label><%= f.radio_button :star, 2 %> 2</label>
    <label><%= f.radio_button :star, 3 %> 3</label>
    <label><%= f.radio_button :star, 4 %> 4</label>
    <label><%= f.radio_button :star, 5 %> 5</label>
<-! Up to here ->
  <%= f.submit "POST IT!" %>
<% end %>

3. Fix the controller

If you are using an action to receive a parameter in the create action like this Let’s add a star column


  def post_params

4. Write stars on the Index page

Finally, we will display the stars with a for sentence! !!


<% @posts.each do |t| %>
   <div class="index-name">
        <%= t.name %>
   <-! Additions ->
   <div class=“star-bar”>
<% for i in 1..t.star do%>
   <-! Additions ->

This completes the Hoshigo function! !!

Tags: ,