动作索引中 nil:NilClass 的未定义方法“round”
undefined method `round' for nil:NilClass in action index
我是新手 rails 我正在尝试在操作索引页面中使用 Rating Star,但我遇到了这个错误
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 in action INDEX Page
.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
在您的 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
我是新手 rails 我正在尝试在操作索引页面中使用 Rating Star,但我遇到了这个错误
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 in action INDEX Page
.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
在您的 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