动作索引中nil:NilClass的未定义方法“回合”

时间:2018-06-26 02:40:26

标签: ruby-on-rails ruby-on-rails-5 ruby-on-rails-5.2

我是新手,正在尝试在行动索引页中使用“星级评分”,但出现此错误

def index
  @listings = Listing.all.order("created_at desc")
end

def show
  impressionist(@listing, nil, { unique: [:session_hash] })
  @reviews =  @listing.reviews.order("created_at DESC")
  unless @reviews.present?
    @avg_review = 0
  else
    @avg_review = @reviews.average(:rating).present? ? @reviews.average(:rating).round(2) : 0
  end
end

实际操作中的HAML CODE索引页面

.geodir-category-options.fl-wrap
  .listing-rating.card-popup-rainingvis.star-rating{"data-score" => "#{listing.reviews.average(:rating).round(2)}"}
    %span{style: "float:right"}
      =listing.reviews.count                        

1 个答案:

答案 0 :(得分:2)

在index.html.haml中,您还应该按照在控制器中显示的方法进行过滤,所以不要:

listing.reviews.average(:rating).round(2)

应该是:

listing.reviews.average(:rating).present? ? listing.reviews.average(:rating).round(2) : 0

完整代码:

.geodir-category-options.fl-wrap
  .listing-rating.card-popup-rainingvis.star-rating{"data-score" => "#{listing.reviews.average(:rating).present? ? listing.reviews.average(:rating).round(2) : 0}"}
    %span{style: "float:right"}
      =listing.reviews.count