【问题标题】:Fetching all posts made by a user with Devise gem使用 Devise gem 获取用户发布的所有帖子
【发布时间】:2014-09-29 11:54:51
【问题描述】:

我正在使用 Devise 来管理用户模型。

这是用户模型,user.rb

class User < ActiveRecord::Base
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable

  acts_as_voter
  has_many :topics

  devise :database_authenticatable, :registerable,
     :recoverable, :rememberable, :trackable, :validatable        

end

这里是主题模型,topic.rb

class Topic < ActiveRecord::Base
    acts_as_voteable
    belongs_to :user
end

当我创建帖子时,用户 ID 存储在主题的“user_id”列中。我想要一个用户个人资料页面,该页面应该显示他发布的所有帖子。在我的用户个人资料页面视图中,我有,

<%= Topic.find_by_user_id(@user.id) %>

我有两个帖子由同一个用户发,

但是当我尝试获取用户发布的所有帖子时,SQL 命令会自动查询 LIMIT 为 1。就像这样,

因此,视图仅获取用户发布的 1 个帖子。如何获取所有帖子?

【问题讨论】:

    标签: sql ruby-on-rails ruby activerecord devise


    【解决方案1】:

    find_by_attribute 将始终只返回一个结果。您需要将代码更改为:

    Topic.where(user_id: @user.id)
    

    甚至更好:

    @user.topics
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-05-02
      • 2020-06-04
      • 1970-01-01
      • 2016-12-24
      • 1970-01-01
      • 2018-08-16
      • 2011-07-06
      相关资源
      最近更新 更多