我想在页面上只显示facebook url,twitter url。在表格中链接了大约40个网址,用于不同的网站,社交网络。
我的代码:
<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
我不喜欢这样。有什么更优雅的方式来实现这个任务
答案 0 :(得分: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>
编辑:当然应该添加ul标签
答案 1 :(得分:1)
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>