У меня есть приложение Ruby on Rails, которое должно помочь в обзоре больниц.
Я следовал подробному руководству по созданию и созданию довольно работоспособного приложения.
Я пытаюсь добавить еще несколько новых функций в приложение
- Я бы хотел, чтобы пользователи видели список больниц в базе данных с домашней страницы, четко показывая название больницы, изображение и средние отзывы
Я могу успешно отображать больницы, изображения и номера телефонов на индексной странице / странице дома, но изо всех сил пытаюсь показать средний рейтинг всех отзывов по больнице.
Это странно, потому что у меня точно такая же структура на страницах отдельных больничных шоу, и там все отлично работает.
Я чувствую, что нахожусь всего в нескольких шагах и нуждаюсь в помощи. Пожалуйста, смотрите фрагменты кода ниже:
index.html.erb
<div class="jumboFluid">
<div class="jumbotron">
<section class="content">
<%= form_tag search_hospitals_path, method: :get, class: "form-group" do %>
<div class="input-group">
<div class="input-group-addon">Search</div>
<p>
<%= text_field_tag :search, params[:search], class: "form-control formInput", placeholder: "Eye, Maternity" %>
<%# <%= submit_tag "Search", name: nil, class: "btn btn-default" %>
</p>
</div>
</div>
<% end %>
</section>
</div>
</div>
<div class="hospitalList">
<h1 id="hospitalBanner">Hospitals</h1>
<blockquote>
<p class="text-center"><cite>“Explore the best of healthcare available in your community”</cite> </p>
</blockquote>
<% content_for(:body_attributes) do %>
data-no-turbolink="false"
<% end %>
<div class="container-fluid">
<div class="row">
<% @hospitals.each do |hospital| %>
<div class="col-md-3">
<div class="thumbnail">
<%= link_to image_tag(hospital.image), hospital %>
<div class="caption">
<p> <%= link_to hospital.name, hospital %></p>
<p> <%= hospital.phone %></p>
</div>
</div>
</div>
<% end %>
</div>
<br>
<% if user_signed_in? && current_user.admin? %>
<%= link_to 'New Hospital', new_hospital_path, class: "btn btn-link" %>
<% end %>
<script>
$('.star-rating').raty({
path: 'https://s3-us-west-2.amazonaws.com/morafamedapp/stars',
readOnly: true,
score: function() {
return $(this).attr('data-score');
}
});
</script>
</div>
Рабочий код выставки
show.html.erb
<div class="row">
<div class="col-md-3">
<%= image_tag @hospital.image_url unless @hospital.image.blank? %>
<h3>
<%= @hospital.name %>
</h3>
<div class="star-rating" data-score= <%= @avg_rating %> ></div>
<p><%= "#{@reviews.length} reviews" %></p>
<%= social_share_button_tag("Share") %>
<p>
<strong>Address:</strong>
<%= @hospital.address %>
</p>
<p>
<strong>Phone:</strong>
<%= @hospital.phone %>
</p>
<p>
<strong>Website:</strong>
<%= link_to @hospital.website, @hospital.website, target: :_blank %>
</p>
<%= link_to "Write a Review", new_hospital_review_path(@hospital), class: "btn btn-primary" %>
<br>
<br>
<iframe width="230" height="230" frameborder="0" style="border:0"
src="https://www.google.com/maps/embed/v1/place?q=<%= @hospital.address.parameterize %>&key=AIzaSyAc4mTzAGIA_8JFXAcL3XTBi-tzuxQCsBc" allowfullscreen></iframe>
</div>
<div class="col-md-9">
<% if @reviews.blank? %>
<h3>No reviews yet. Be the first to write one!</h3>
<% else %>
<table class="table">
<thead>
<tr>
<th class="col-md-3"></th>
<th class="col-md-9"></th>
</tr>
</thead>
<tbody>
<% @reviews.each do |review| %>
<tr>
<td>
<h4>
<%= "#{review.user.first_name.capitalize} #{review.user.last_name.capitalize[0]}." %>
</h4>
<p><%= review.created_at.strftime("%-d/%-m/%y") %></p>
</td>
<td>
<div class="star-rating" data-score= <%= review.rating %> ></div>
<p><%= h(review.comment).gsub(/\n/, '<br/>').html_safe %></p>
<%= social_share_button_tag("Share") %>
<% if user_signed_in? %>
<% if (review.user == current_user) || (current_user.admin?) %>
<%= link_to "Edit", edit_hospital_review_path(@hospital, review) %>
<%= link_to "Delete", hospital_review_path(@hospital, review), method: :delete %>
<% end %>
<% end %>
</td>
</tr>
<% end %>
</tbody>
</table>
<% end %>
</div>
</div>
<%= link_to 'Edit', edit_hospital_path(@hospital), class: "btn btn-link" %> |
<%= link_to 'Back', hospitals_path, class: "btn btn-link" %>
<script>
$('.star-rating').raty({
path: 'https://s3-us-west-2.amazonaws.com/morafamedapp/stars',
readOnly: true,
score: function() {
return $(this).attr('data-score');
}
});
</script>
hospital.rb
class Hospital < ApplicationRecord
mount_uploader :image, ImageUploader
searchkick
has_many :reviews
def self.import(file)
CSV.foreach(file.path, headers: true) do |row|
Hospital.create! row.to_hash
end
end
def self.avg_rating
Hospital.avg_rating
end
end
show.html.erb
<h3>
<%= @hospital.name %>
</h3>
<%= @hospital.avg_rating %>
<p><%= "#{@reviews.length} reviews" %></p>
Error
Showing /Users/oluwaseunmorafa/medaapp1/app/views/hospitals/show.html.erb where line #9 raised:
undefined method `avg_rating' for #<Hospital:0x007fd846496ee0>
Extracted source (around line #9):
7
8
9
10
11
12
</h3>
<%= @hospital.avg_rating %>
<p><%= "#{@reviews.length} reviews" %></p>