Rails - 显示用户关注的上个月发布图书的用户



很抱歉这个问题,我还在学习轨道。我试图在我的 html 中显示 - 用户开始关注的所有用户,这些用户在上个月发布了一本书(即您关注的最近发布了一本书的用户(。我尝试遵循我从这个问题中学到的教训 Rails - 显示用户在上个月开始关注的用户 - 但我无法让它工作并得到一个错误的未定义方法 'books' for #.非常感谢您的帮助。

以下.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

用户.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

首先,有很多东西可以简化。这些行:

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

以防其他人遇到类似的问题。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。

第三,我正在使用"&"的力量将我关注的那些user_ids与最新书籍的用户ID进行比较

第四,我与我的用户共同创造@newpostuser。这:)

最新更新