我正在使用rails(5.2.3),并尝试显示所有标记有特定类别的广告,但索引为空
show.html.erb(category_view)
<% @category.ads.each do |ad| %>
<%= ad.category.try(:label) %>
<%= ad.title %>
<%= ad.user.first_name %>
<%= ad.publishing_at.strftime("%Y-%m-%d") %>
<%= ad.location %>
<%= ad.price %>
<%= ad.description %>
<% end %>
Category.rb
class Category < ApplicationRecord
has_many :ads
belongs_to :categorytype
end
Ad.rb
class Ad < ApplicationRecord
belongs_to :user
belongs_to :category
end
Categories_controller.rb
class CategoriesController < ApplicationController
def show
@category = Category.find(params[:id])
@ads = @category.ads.published.paginate(page: params[:page], per_page: 5)
end
任何解决方案吗?
答案 0 :(得分:0)
替换
@ads = @category.ads.published.paginate(page: params[:page], per_page: 5)
使用
@ads = @category.ads&.published&.paginate(page: params[:page], per_page: 5)
并在视图中
<% @ads.each do |ad| %>
<%= ad.category.try(:label) %>
<%= ad.title %>
....
<% end %>