问题
Apologies for the question, I'm still learning rails. I'm trying to show in my html - all the users that a user has started following within the last month (i.e. recent users you've followed). I've tried two approaches-both unsuccessful. My first try was in my controller but the closest I got was showing users I've started following who were created in the last month. My second try was in my user model - but I get undefined method `call' for # Did you mean? caller
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:
I'd go for the controller solution.
But the matter is that I will be looking for the relation creation time, not the user (it is user, right, I mean Follower is User model, right?).
So:
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
来源:https://stackoverflow.com/questions/43029961/rails-show-the-users-that-a-user-started-following-in-the-last-month