我知道这应该很简单,但我是ruby,haml和rails的新手。
我想显示特定律师的位置列表。我想将它们转换成'to_sentence',所以除了最后一个位置之外的每个位置都有逗号。
这就是我在show.html.haml
视图中的内容。
%ul
- @lawyers.each do |lawyer|
- if lawyer == @lawyer
%li.active
%article
%h3= lawyer.full_name
- unless lawyer.phone.nil?
.phone== Direct #{lawyer.phone}
.email
= mail_to lawyer.email, lawyer.email
- unless @lawyer.office_locations.empty?
- if @lawyer.office_locations.count > 1
.locations_list
%ul
%li Locations:
- @lawyer.office_locations.each do |office_location|
%li.locations== #{office_location.city}
- else
.locations_list
%ul
%li Location:
- lawyer.office_locations.each do |office_location|
%li== #{office_location.city}
编辑: 这就是我的尝试。
- unless @lawyer.office_locations.empty?
- if @lawyer.office_locations.count > 1
.locations_list
%ul
%li Locations:
%li== lawyer.office_locations.collect{ |p| "#{p.office_locations.city}"}.to_sentence
我不知道它是否有所不同,但lawyer
和office_location
是两个单独的模型,它们都是HABTM。
我知道这是错误的做法,但我似乎无法让to_sentece
或.pluralize
工作。我尝试使用这篇文章中的答案Ruby on Rails seems to be auto-escaping html created by link_to,但我无法使其发挥作用。
我假设我可能想把这个逻辑放在帮助器里?任何帮助将不胜感激。
答案 0 :(得分:2)
这一行有一个问题:
%li== lawyer.office_locations.collect{ |p| "#{p.office_locations.city}"}.to_sentence
您正在.office_locations
关系中的每个p
上致电lawyer.office_locations
。我怀疑你想要阻止{ |p| "#{p.city}"}
。
如果要复数“Location / s”,可以使用参数调用pluralize方法:
"Location".pluralize(1)
将返回“位置”,并且
"Location".pluralize(2)
(或大于1的任何内容)将返回“地点”。因此,您可以将其添加到模板中:
%li= "Location".pluralize(lawyer.office_locations.count)