ruby-on-rails - 用户镜头 - 如何仅显示您关注的用户的镜头(不包括我自己的)
问题描述
如何仅显示您关注的用户(不包括我自己的用户)的照片?我认为问题出在提要中,但我是 Rails 的新手,不知道该怎么做。感谢开发者!
[enter image description here][1]
my user.controller
class User < ApplicationRecord
friendships, class_name: "Friendship", foreign_key: "follower_id", dependent: :destroy
has_many :passive_friendships, class_name: "Friendship", foreign_key: "followed_id", dependent: :destroy
has_many :followings, through: :active_friendships, source: :followed
has_many :followers, through: :passive_friendships, source: :follower
#follow another user
def follow(other_user)
active_friendships.create(followed_id: other_user.id)
end
#Unfollow a other_user
def unfollow(other_user)
active_friendships.find_by(followed_id: other_user.id).destroy
end
#Is following a other_user?
def following?(other_user)
following_ids.include?(other_user.id)
end
def feed
following_ids = "SELECT followed_id FROM Friendships WHERE follower_id = :user_id"
Shot.where("user_id IN (#{following_ids}) OR user_id = :user_id", user_id: id)
end
my show.html.erb
<div class="shots user">
<% @user.feed.each do|shot|%>
<section class="section">
<div class="shot-grid-item">
<div class="shot-wrapper">
<%= link_to shot, class: "shot" do %>
<% if shot.user_shot_url.present? %>
<%= cl_image_tag(shot.user_shot_url) %>
<% else %>
<label><%= shot.description %></label>
<div class="shot-data">
<h3 class="shot-title"><%= shot.title %></h3>
<div class="shot-description"><%= truncate(shot.description, length: 60) %></div>
<div class="shot-time">
<%= time_ago_in_words(shot.created_at) %>
</div>
</div>
<% end %>
<% end%>
</div>
解决方案
你可以做类似的事情
<%= current_user.followings.shots.each do |shot| %>
<% end %>
更好 - 您可以在控制器中声明一个从视图中提取此逻辑的变量:
@following_shots = current_user.followings.shots
然后在视图中
<%= @following_shots.each do |shot| %>
<% end %>
推荐阅读
- node.js - 实时编辑源代码时Nodejs崩溃,如何停止这种行为
- c++ - 使用哈希映射在c ++中查找字符串中的第一个唯一元素的问题
- arrays - 过滤独特的结果以减少数量并按最新的 Google 表格对这些结果进行排序
- javascript - 在 Adobe Acrobat Pro XII 中保留前导零
- html - AlpineJS - preventDefault 触发事件
- python-3.x - 用 python 3 修改 mule XML 文件
- haskell - 如何删除 Haskell 中的守卫中的解析错误?
- sql - SQL将值添加到特定位置的单元格中
- memory - 我应该为我的 TimesTen 数据库使用大页面吗?如果是,我该如何配置它?
- c++ - 歧义运算符<< Clang 中的重载