【问题标题】:Devise: I can't display only current user workouts设计:我不能只显示当前用户的锻炼
【发布时间】:2017-01-09 02:34:25
【问题描述】:

我创建了一个小运动应用程序,现在我无法在索引页面上仅显示当前用户的锻炼情况。

问题: WorkoutsController#index 中的 NoMethodError。 nil:NilClass 的未定义方法“锻炼”。

def index
    @workouts = current_user.workouts.all
end

我将所有详细信息留在下面:

协会

  1. 在我的用户模型中,我有

    has_many :锻炼

  2. 在我写的锻炼模型中

    belongs_to :user

  3. 在我看来/workouts/index.html.erb

    <% @workouts.each do |workout| %>
        <h4><%= link_to workout.date, workout %></h4>
        <h3><%= workout.workout %></h3>
    <% end %>
    

【问题讨论】:

  • 您错过了在控制器中添加before_filter :authenticate_user! 吗?
  • 表示current_user为nil(你还没有登录)
  • 关系似乎没问题。检查 current_user。尝试使用 puts current_user.inspect 进行检查。检查它给出的内容,它必须为空
  • 在我的锻炼控制器中我有 -> before_action :authenticate_user!,除了:[:index, :show]

标签: ruby-on-rails ruby activerecord devise


【解决方案1】:

试试这个:

def index
    @workouts = current_user.present? ? current_user.workouts : []
end

我认为您未登录时有错误,current_user 返回 nil

【讨论】:

  • 最好使用 before_filter :authenticate_user!防止这种异常
  • 当你使用 :authenticate_user 时!对于未登录的用户,您将无法访问 index ...
  • 如果您阅读问题,您会看到锻炼属于用户。并且在没有用户的情况下无法显示。
  • 它工作正常。感谢您的回答。为了更好地理解,您能否描述一下这段代码究竟是如何为我工作的?
  • 是的,current_user.present? ?检查用户是否登录,如果是,则返回current_user.workouts,如果不是,则返回空数组
【解决方案2】:

如果您想获取 current_user 的锻炼列表,则应定义 current_user。这意味着您需要登录。您可以使用前置过滤器轻松检查

before_filter :authenticate_user!

在你使用你的代码之后

@workouts = current_user.workouts.all

如果您想显示其他用户的锻炼情况,您可以跳过过滤器以获取新操作

class TestController < ApplicationController

  before_filter :authenticate_user!, except: [:another_index]

  def another_index
    @workouts = User.find(params[:id]).workouts.all
  end

end

【讨论】:

  • 我的锻炼控制器中有 -> before_action :authenticate_user!,除了:[:index, :show]。这很令人沮丧,因为我在其他项目中做了类似的只显示当前用户的帖子,但我对这个应用程序感到很挣扎。 Gladis 代码对我有用。感谢所有的答案。祝你有美好的一天。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-25
  • 2020-05-15
  • 2019-09-15
  • 2022-09-24
相关资源
最近更新 更多