对于这个问题道歉,我还在学习铁路。我试图在我的HTML中显示 - 用户已经开始关注的所有用户在过去一个月内已经发布了一本书(即您最近发布过一本书的用户)。我已经尝试过从这个问题中学到的经验教训Rails - Show the users that a user started following in the last month - 但是我无法让它工作并得到错误未定义的方法`书'为#。非常感谢你的帮助。
following.html.erb
<div id="wall" class="tab-pane fade">
<% @newpostuser.each do |newpost| %>
<div class="box">
<center>
<%= image_tag newpost.avatar, width: 85 %>
</center>
</div>
<% end %>
</div>
Users_controller.rb
def following
@user = User.find(params[:id])
following_ids = @user.active_relationships.map(&:followed_id)
@userfollowing = User.where(id: following_ids)
newbook_user_ids = @userfollowing.books.where(created_at: (Time.now - 3.month)..Time.now)
@newpostuser = User.where(id: newbook_user_ids)
end
User.rb
has_many :books, dependent: :destroy
has_many :active_relationships, class_name: "Relationship", foreign_key: "follower_id", dependent: :destroy
has_many :passive_relationships, class_name: "Relationship", foreign_key: "followed_id", dependent: :destroy
has_many :following, through: :active_relationships, source: :followed
has_many :followers, through: :passive_relationships, source: :follower
def follow(other)
active_relationships.create(followed_id: other.id)
Notification.create(recipient: @user, actor: User.current_user, action: "Followed", notifiable: @user)
end
def unfollow(other)
active_relationships.find_by(followed_id: other.id).destroy
end
def following?(other)
following.include?(other)
end
答案 0 :(得分:1)
首先,您可以简化很多。这些行:
following_ids = @user.active_relationships.map(&:followed_id)
@userfollowing = User.where(id: following_ids)
可以写成:
@userfollowing = @user.followed
下一个问题是books
方法适用于单个用户(它为一个用户返回书籍),但您尝试将其应用于用户列表。如果它确实有效,它将返回一个不是用户的书籍列表。在你的情况下,你应该写:
@newpostusers = @userfollowing.joins(:books).where(books: { created_at: (Time.now - 3.month)..Time.now) } )
通常,您希望尝试避免使用id
s
答案 1 :(得分:0)
如果其他人遇到类似问题。 Marc的解决方案在一秒钟内运行良好但后来停止工作,给我一个错误,列在下面
undefined method joins' for [3,4,5]:Array Did you mean? join
经过两个小时的尝试,我找到了一个解决方案 - 可能有一种更有效的方法来做到这一点,但这对我来说真的很棒。
def following
@user = User.find(params[:id])
userfollowing = @user.active_relationships.map(&:followed_id)
recentbook = Book.where(created_at: (Time.now - 1.month)..Time.now)
uidsrecentbook = recentbook.map(&:user_id)
common = (userfollowing & uidsrecentbook)
@newpostuser = User.where(id: common)
end
要解释这里发生了什么:
首先,我收集了最近创作的书籍。
其次,我正在使用地图搜索这些近期图书的用户ID。
第三,我使用&#34;&amp;&#34;
的强大功能,将我跟随的用户ID与最新图书的用户ID进行比较。第四,我与我的用户共同创建@newpostuser。这非常有效:)