RoR:如何检索关系或集合的各个属性



我想列出我正在关注的用户

我的型号:

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值。

最新更新