will_paginate无效,返回未定义方法`total_pages'的错误

时间:2016-04-16 05:41:43

标签: ruby-on-rails ruby ruby-on-rails-3 ruby-on-rails-4 rubygems

我正在尝试对微博进行分页。我使用以下内容:     <%= will_paginate @ user.microposts%> 但它返回错误: 未定义的方法`total_pages'为# 请帮忙 我的控制器方法如下:

class UsersController < ApplicationController
  before_filter :signed_in_user, only: [:index,:edit, :update]
  before_filter :correct_user, only: [:edit, :update]
  before_filter :admin_user, only: :destroy
  def index
    @users = User.paginate(page: params[:page])
    @microposts = @user.microposts.paginate(page: params[:page])
  end
  def new
     @user = User.new
  end
  def show
     @user = User.find(params[:id])
  end
  def destroy
    User.find(params[:id]).destroy
    flash[:success] = "User destroyed."
    redirect_to users_path
  end
  def update
    @user = User.find(params[:id])  
    if params[:user].present? &&    @user.update_attributes(params.require(:user).permit(:name,:password,  :password_confirmation))
   flash[:success] = "Profile updated"
   sign_in @user
   redirect_to @user
   else
    render 'edit'
   end
  end


  def edit
    @user = User.find(params[:id])  
    if params[:user].present? &&    @user.update_attributes(params.require(:user).permit(:name,:password, :password_confirmation))
    flash[:success] = "Profile updated"
    sign_in @user
    redirect_to @user
    else
     render 'edit'
    end
   end

  def create
    @user=  User.create(user_params)
    if @user.save
    sign_in @user
    flash[:success] = "Welcome to the Sample App!"
    redirect_to @user
    else
     render 'new'
    end
   end


   private
     def user_params
       params.require(:user).permit(:password, :password_confirmation,   :email,:name)
     end 
   private
     def signed_in_user
      unless signed_in?
      store_location
      redirect_to signin_path, notice: "Please sign in." 
     end
    end
  def correct_user
    @user = User.find(params[:id])
    redirect_to(root_path) unless current_user?(@user)
  end
 end  

3 个答案:

答案 0 :(得分:0)

此处:@microposts = @user.microposts.paginate(page: params[:page])

@user未在index内定义,也未在任何before_filter中设置(如果您使用的是Rails 4. *,before_action是新语法。{{1在Rails 5中是deprecated

编辑:@Sukanta对视图是正确的

答案 1 :(得分:0)

你可以试试这个

<%= will_paginate @microposts %> 

代替

<%= will_paginate @user.microposts %> 

答案 2 :(得分:0)

before_filter :correct_user, only: [:edit, :update]表示correct_user方法仅适用于编辑和更新方法。对于使用它的索引方法,您需要将索引方法添加到列表中。即, before_filter :correct_user, only: [:index, :edit, :update] 并且,也使用before_action而不是before_filter。