未定义的方法`total_pages&#39;对于#<advertisement :: activerecord_relation:0x007fe4cdd7df98>

时间:2017-07-30 11:05:04

标签: ruby-on-rails ruby will-paginate

我正在尝试搜索标签,它运行正常。但是在我开始使用gem will_paginate进行分页后,我无法做到这一点,因为我收到了这个错误:

undefined method 'total_pages' for #<Advertisement::ActiveRecord_Relation:0x007fe4cdd7df98>

但是,如果我搜索一个未知的标签,它可以正常工作(在索引页面上显示一个空的广告列表)。

advertisemts_controller.rb

class AdvertisementsController < ApplicationController
  before_action :authenticate_user!
  before_action :set_advertisement, only: %i[edit update destroy]

  def index
    @advertisements = Advertisement.paginate(page: params[:page], 
    per_page: 2)
  end

  def show
    @advertisement = Advertisement.find(params[:id])
  end

  def new
    @advertisement = Advertisement.new
  end

  def create
    @advertisement = Advertisements::Create.call(advertisement_params)

    if @advertisement.errors.blank?
      redirect_to advertisement_path(@advertisement),
                notice: 'The advertisement was successfully added.'
    else
      render action: 'new'
    end
  end

  def update
    if @advertisement.update(advertisement_params)
      redirect_to @advertisement, notice: 'Advertisement was 
                                           successfully updated.'
    else
      render :edit
    end
  end

  def destroy
    @advertisement.destroy
    redirect_to advertisements_path, notice: 'Advertisement was 
  successfully destroyed.'
  end

  private

  def set_advertisement
    @advertisement = current_user.advertisements.find(params[:id])
  end

  def advertisement_params
    params
      .require(:advertisement)
      .permit(:title, :description, :user_id, :tags)
      .merge(user_id: current_user.id)
  end
end

search_queries_controller.rb

class SearchQueriesController < ApplicationController
  def search_by_tag
    @advertisements = Advertisement.find_by_tags(tags_params)

    render 'advertisements/index'
  end

  private

  def tags_params
    params.fetch(:tags, '')
  end
end

advertisement.rb

class Advertisement < ApplicationRecord
  has_many   :advertisement_tags, dependent: :destroy
  has_many   :comments
  has_many   :tags, through: :advertisement_tags
  belongs_to :user

  validates :title,
            :description,
            presence: true

  def self.find_by_tags(tags)
    Advertisement.joins(:tags).where('tags.tag_name IN (?)', 
                                      tags.split(/[\s,']/))
  end
end

我不知道如何解决这个问题,我使用ruby-2.3.4rails-5.1.2will_paginate-3.1

1 个答案:

答案 0 :(得分:0)

那是因为

def search_by_tag
  @advertisements = Advertisement.find_by_tags(tags_params)

  render 'advertisements/index'
end

不会在关系上调用paginate方法,但会渲染使用分页的视图。

您甚至可能会注意到Advertisement.all.paginate(page: 1).total_pages有效,但Advertisement.all.total_pages没有。

这样的东西
def search_by_tag
  @advertisements = Advertisement
    .find_by_tags(tags_params)
    .paginate(page: 1, per_page: 2)

  render 'advertisements/index'
end

应解决问题