0

我知道这应该很简单,但我是 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 似乎是由 link_to 创建的自动转义 html,但我无法让它工作。

我假设我可能想把这个逻辑放在一个助手中?任何帮助,将不胜感激。

4

1 回答 1

2

这一行有一个问题:

%li== lawyer.office_locations.collect{ |p| "#{p.office_locations.city}"}.to_sentence

您正在从关系中调用.office_locations每个。我怀疑你想要这个块。plawyer.office_locations{ |p| "#{p.city}"}

如果你想复数“Location/s”,你可以用一个参数调用复数方法: "Location".pluralize(1)将返回“Location”,并且 "Location".pluralize(2)(或任何大于 1 的值)将返回“Locations”。因此,您可以将其添加到您的模板中:

%li= "Location".pluralize(lawyer.office_locations.count)
于 2013-03-04T19:38:09.183 回答