1

我正在尝试在我的一个模型中创建一个列,该模型使用请求用户的 id 来生成列。我从请求标头中获取当前用户:

# app/controllers/posts_controller.rb

if request.headers['Authorization']
  token_string = request.headers['Authorization']
  current_user = User.where(token: token_string).take
end

我在使用的模型中创建了一个方法current_user

# app/models/post.rb

attr_accessor :user_voted

def user_voted(current_user)
  if current_user
    return PostVote.where(post_id: self[:id], user_id: current_user[:id]).size > 0
  else
    return false
  end
end

在控制器中渲染之前,我会:

@articles = Article.where(safe_params)
      .order(order)
      .limit(10)
      .offset(offset)

@articles.user_voted current_user

当我尝试运行它时出现以下错误:

NoMethodError (undefined method `user_voted' for #<Post::ActiveRecord_Relation:0x00000003b8fbe8>):
  app/controllers/posts_controller.rb:55:in `index'

将控制器信息传递给模型的正确方法是什么?

4

1 回答 1

0

@articles是 的实例Post::ActiveRecord_Relation,而不是 的实例Post。因此,您必须将 thecurrent_user合并到where控制器中的子句中。

@articles = Article.where(safe_params)
                   .order(order)
                   .limit(10)
                   .offset(offset)

@did_user_vote = @articles.joins(:post_votes)
                          .where(post_votes: { user_id: current_user.id })
                          .exists?

因此,您在查询中加入post_votes关系@articles,并查找PostVotes该用户的帖子。

于 2016-01-16T20:59:15.153 回答