【问题标题】:Using to_sentence with HAML and mongoid将 to_sentence 与 HAML 和 mongoid 一起使用
【发布时间】:2013-02-19 00:03:45
【问题描述】:

我知道这应该很简单,但我是 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 上的答案,但无法正常工作。

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

【问题讨论】:

  • 请发布不起作用的代码 - 在您的示例中我既没有看到 to_sentence 也没有看到 pluralize。

标签: ruby-on-rails ruby haml


【解决方案1】:

这行有问题:

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

您正在对来自 lawyer.office_locations 关系的每个 p 调用 .office_locations。我怀疑你希望区块是{ |p| "#{p.city}"}。

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

%li= "Location".pluralize(lawyer.office_locations.count)

【讨论】:

  • 这将是一个愚蠢的问题。 |p| 中的 p 指的是什么?我不确定在这里使用什么,或者我是否需要先在其他地方定义它。你的代码对我不起作用,我认为这是我的问题的一部分。
  • .collect 是一个迭代器,因此块参数(在本例中为p)引用office_locations 集合的每个成员,因为该成员调用了该块。通常建议更语义化地命名参数,如office_locations.collect {|location| "#{location.city}" }。
  • 谢谢@Zach 我得到了 to_sentence 的工作。但是当我尝试%li= "Location".pluralize(lawyer.office_locations.count) 时,我得到了错误wrong number of arguments (1 for 0)
猜你喜欢
  • 1970-01-01
  • 2012-11-18
  • 2013-09-26
  • 1970-01-01
  • 1970-01-01
  • 2012-03-30
  • 2012-10-28
  • 2010-12-21
  • 2010-10-10
相关资源
最近更新 更多