Reputation:
I have an if statement in a loop that only displays posts from users followers:
<% @posts.each do |post| %>
<% if post.user.following?(current_user) && current_user.following?(post.user) %>
<%= post.body %>
<% end %>
<% end %>
And this is my controller code for that loop:
@posts = Post.where('created_at >= :one_day_ago', one_day_ago: Time.now - 24.hours).order("created_at DESC")
Is there a way to get the if statement into my controller code?
Upvotes: 1
Views: 44
Reputation: 230471
Is there a way to get the if statement into my controller code?
Sure, it could look like this:
@posts = Post.where('created_at >= :one_day_ago', one_day_ago: Time.now - 24.hours).order("created_at DESC")
@posts = @posts.filter do |post|
post.user.following?(current_user) && current_user.following?(post.user)
end
Then in your view you just render the filtered posts:
<% @posts.each do |post| %>
<%= post.body %>
<% end %>
Upvotes: 3