[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
  end
end

I will migrate.

rails db:migrate

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

schema.rb



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

html:posts/new.html.erb



<%= form_for @posts do |f| %>
  <div class="field">
  <p>
    <%= f.label :name %>
    <%= f.text_field :name %>
   
  </p>
<-! Added part ->
  <p>
   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>
   </p>
<-! Up to here ->
  </div>
  <%= 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

posts_controller.rb



private
  def post_params
    params.require(:posts).permit(:name,:star)
  end

4. Write stars on the Index page

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

html:posts/index.heml.erb



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

This completes the Hoshigo function! !!

Tags: ,

Updated: