Here's how to implement a 5-star rating on your store and meal 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 below.
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"
If it is written, it's OK!
We will be able to send the number "2" for 2 stars and "5" for 5 stars. Anything is fine 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 star rating:
<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>
<-!So far->
</div>
<%= f.submit "POST IT!" %>
<% end %>
If you are using an action to receive a parameter in the create action, Let's add a star column
posts_controller.rb
private
def post_params
params.require(:posts).permit(:name,:star)
end
Finally, the for statement will display the stars! !!
html:posts/index.heml.erb
<% @posts.each do |t| %>
<div class="index-name">
<%= t.name %>
</div>
<-!Additional points->
<div class=“star-bar”>
<%for i in 1..t.star do%>
★
<%end%>
</div>
<-!Additional points->
<%end%>
This completes the five-star function! !!
Recommended Posts