获取用户使用Devise创建的所有贴子
问题描述:
我正在使用Devise来管理用户模型。获取用户使用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命令的1这样的LIMIT自动查询,
也正因为如此,该视图fetchin g只有1个用户发表的帖子。我如何获取所有帖子?
答
find_by_attribute
将始终只返回一个结果。您需要将代码更改为:
Topic.where(user_id: @user.id)
甚至更好:
@user.topics