Stefan Hansch Stefan Hansch - 7 months ago 11
Ruby Question

How to quickly select items from the list that correspond to elements of the array

I want display on page only facebook url, twitter url. In Table links about 40 urls for different messegers, social networks.

My code:

<ul class="icons-bar icons-bar_socials icons-bar_socials_profile">
<% @freelancer.links.each do |link| %>
<% if link.messenger_type.title == "facebook" %>
<li class="icons-bar__item">
<%= link_to link.url, link.url, class: "icons-bar__icon icon_faceebook" %>
</li>
<% end %>
<% if link.messenger_type.title == "twitter" %>
<li class="icons-bar__item">
<%= link_to link.url, link.url, class: "icons-bar__icon icon_twitter" %>
</li>
<% end %>
</ul>


list.rb

# == Schema Information
#
# Table name: links
#
# id :integer not null, primary key
# url :string
# freelancer_id :integer
# messenger_type_id :integer
#
# Indexes
#
# index_links_on_freelancer_id (freelancer_id)
# index_links_on_messenger_type_id (messenger_type_id)
#

class Link < ApplicationRecord
belongs_to :freelancer
belongs_to :messenger_type

end


messenger_type.rb

# == Schema Information
#
# Table name: messenger_types
#
# id :integer not null, primary key
# title :string
# created_at :datetime not null
# updated_at :datetime not null
#

class MessengerType < ApplicationRecord
has_many :links
end


I do not like this the way. What is there a more elegant way to implement this task

Answer

I think this is more clear and also remove unnecessary conditionals.

You can also put it in a helper if you want.

<ul class="icons-bar icons-bar_socials icons-bar_socials_profile">
  <% @freelancer.links.select{|link| ["twitter", "facebook"].include? link.messager_type.title  }.each do |link| %>      
      <li class="icons-bar__item">
        <%= link_to link.url, link.url, class: "icons-bar__icon icon_#{link.messager_type.title}" %>
      </li>
  <%end%>         
</ul>