2016-04-15 7 views
0

ページ専用のfacebook url、twitter urlに表示したい。テーブルのリンクでは、さまざまなメッセンジャー、ソーシャルネットワークの約40のURL。リストから素早く配列の要素に対応する項目を選択する方法

マイコード:

<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 

私はこの方法が好きではありません。このタスクを実装するために、よりエレガントな方法は何があり

答えて

1

私は、これはまた、より明確であると思いますが追加されている必要がありますもちろん、不要な条件を削除します。

必要に応じてヘルパーに入れることもできます。

<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> 
2

これは、よりエレガントになります:

<ul class="icons-bar icons-bar_socials icons-bar_socials_profile"> 
<% if ['twitter', 'facebook'].include? link.messenger_type.title %>  
     <li class="icons-bar__item"> 
     <%= link_to link.url, link.url, class: "icons-bar__icon icon_#{link.messenger_type.title.downcase}" %> 
    </li> 
    <% end %> 
</ul> 

EDIT:ULタグ

関連する問題