目前,我的平均评分在展示页面中。
但是,除了每个冲浪学校的名字之外,我如何在索引中显示这个平均评分?我遇到了麻烦,因为在索引上,我们使用@ surf_school.each做| surf_schools |。
以下代码是我在展示页面中显示平均评分的代码。
surf_schools_controller.rb
class SurfSchoolsController < ApplicationController
before_action :authenticate_user!, except: [:index, :show]
before_action :surf_school_find, only: [:show, :edit, :update, :destroy]
before_action :correct_user, only: [:edit, :update, :destroy]
def index
@surf_schools = SurfSchool.all
end
def new
@surf_school = current_user.surf_schools.build
end
def create
@surf_school = current_user.surf_schools.build(surf_school_params)
if @surf_school.save
redirect_to surf_schools_path
else
render 'new'
end
end
def show
if @surf_school.surf_school_reviews.blank?
@average_surf_school_review = 0
else
@average_surf_school_review = @surf_school.surf_school_reviews.average(:rating).round(2)
end
end
def edit
end
def update
if @surf_school.update(surf_school_params)
redirect_to surf_schools_path
else
render 'edit'
end
end
def destroy
@surf_school.destroy
redirect_to surf_schools_path
end
private
def surf_school_params
params.require(:surf_school).permit(:name, :country, :location, :phone, :email, :url)
end
def surf_school_find
@surf_school = SurfSchool.friendly.find(params[:id])
end
def correct_user
unless @surf_school.user_id == current_user.id
redirect_to surf_schools_path, notice: "Not authorized to perform this action."
false
end
end
end
show.html.erb
<p><%= link_to "Back", surf_schools_path %></p>
</br>
<h5>Average Rating: </h5>
<div class="average-surf_school_review-rating" data-score=<%= @average_surf_school_review %>></div>
<%= @average_surf_school_review %> (
<%= @surf_school.surf_school_reviews.count %>
<% if @surf_school.surf_school_reviews.count <= 1 %>
review
<% else %>
reviews
<% end %>
)
<p><%= link_to "Add Review", new_surf_school_surf_school_review_path(@surf_school) %></p>
</br>
<p><%= render @surf_school.surf_school_reviews %></p>
<script>
$('.surf_school_review-rating').raty({
readOnly: true,
score: function() {
return $(this).attr('data-score');
},
path: '/assets/'
});
</script>
<script>
$('.average-surf_school_review-rating').raty({
readOnly: true,
path: '/assets/',
score: function() {
return $(this).attr('data-score')
}
});
</script>
这是我的index.html.erb
<% @surf_schools.each do |surf_school| %>
<h2><%= surf_school.name %></h2>
<p>Country: <%= surf_school.country_name %></p>
<p>Location: <%= surf_school.location %></p>
<p>Contact #: <%= surf_school.phone %></p>
<p>E-mail: <%= surf_school.email %></p>
<p>
<%= link_to "Visit Site", surf_school.url, target: "_blank" %>
<%= link_to "Read Reviews", surf_school %>
</p>
<% if current_user == surf_school.user %>
<p>
<%= link_to "Update", edit_surf_school_path(surf_school) %>
<%= link_to "Unlist", surf_school, method: :delete, data: {confirm: "Are you sure?"} %>
</p>
<% end %>
<% end %>
答案 0 :(得分:1)
在索引页面中尝试此操作....
var d = new Date('Mon Feb 08 2016 11:34:25 GMT+0530 (IST)').getTime() \\output : 1454911465000
希望这对你有用。