我想列出我正在关注的用户
我的型号:
Relationship.rb
belongs_to :follower, class_name: "User"
User.rb
has_many :followers, through: :passive_relationships, source: :follower
在我看来
<%= current_user.followers.collect { |follower| follower.username } %>
这在视图中给出:
Following
["Lisa", nil, "Derek"] etc
如何在我的视图中正常列出这些用户?
Lisa
Derek
etc...
当然,这取决于您希望它如何显示。但这很容易,例如,假设您使用erb
进行渲染,则可以使用迭代:
<% current_user.followers.pluck(:username).compact.each do |follower_username| %>
<%= follower_username %>
<br />
<% end %>
请注意,我使用了ARpluck
而不是map
,后者在Rails世界中更有效、更惯用,并且我使用compact
来排除nil
值。