Rails - 显示用户在上个月开始关注的用户

时间:2017-03-26 14:25:00

标签: ruby-on-rails ruby ruby-on-rails-5

对这个问题道歉,我还在学习铁轨。我试图在我的html中显示 - 用户在上个月内开始关注的所有用户(即您已关注的最近用户)。我尝试了两种方法 - 都不成功。 我的第一次尝试在我的控制器中,但我得到的最接近的是显示用户我已经开始关注上个月创建的用户。 我的第二次尝试是在我的用户模型中 - 但是我得到未定义的方法`call'for#您的意思是?呼叫者

following.html.erb

<div class="tab-content">        
<div id="fire" class="tab-pane fade">
        <% @followingurecent.each do |recentfollowing| %>
            <div class="box">
                <center>
                <%= image_tag recentfollowing.avatar, width: 85 %>
                </center>
            </div>
        <% end %>
</div>
</div>

Users_controller.rb

def following
    @user = User.find(params[:id])
    now = Time.now
    @followingurecent = @user.following.where(created_at: (now - 1.month)..Time.now)
end

User.rb

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
def followingrecent
    now = Time.now
    self.following.where(active_relationships.where.(created_at: (now - 1.day)..Time.now))
end

1 个答案:

答案 0 :(得分:1)

我选择控制器解决方案。

但问题是我会寻找关系创建时间,而不是用户(它是用户,对,我的意思是追随者是用户模型,对吧?)。

所以:

def following
    @user = User.find(params[:id])
    # find the follower ids through the relations
    following_user_ids = @user.passive_relationships.where(created_at: (Time.now - 1.month)..Time.now).map(&:follower_id)
    # then get the followers
    @followingurecent = User.where(id: following_user_ids)
end