簡體   English   中英

Ruby:如何根據變量數量在 Active Admin 面板中對單詞進行復數/單數化(Active Admin、rails 3.2、ruby)

[英]Ruby: How to pluralize/singularize a word in Active Admin panel according to variable quantity (Active Admin, rails 3.2, ruby)

我是 Ruby on Rails 的新手,我無法根據單詞的數量更改單詞的結尾。

在下面代碼的頂部附近,你會看到我寫的

h3 "The deal has #{deal.prizes.where(:prize_type => u).count} #{u}

此處的“u”采用名為 PRIZE_TYPE 的數組中的值之一。 我怎么能這樣做

  • 如果count= 1,則顯示“這筆交易有1個頭獎”

  • 如果count=4,則顯示“這筆交易有4個頭獎

注意:計數不能為 = 0 或 < 0

這是我的代碼:

panel "Details of Prizes" do

      PRIZE_TYPES.each do |u|

        table_for deal.prizes.where(:prize_type => u) do |t|
          h3 "The deal has #{deal.prizes.where(:prize_type => u).count} #{u}s
          initially set in the campaign for a total value of #{custom_number_to_currency (deal.category_prizes_total_initial_value(u)) }", class: 'title-within-table'
          if deal.prizes.where(:prize_type => u).count > 0 # if there is at least one record of 'jackpot prize'
            t.column("Prize")             { |prize| link_to( image_tag( prize.prize_image_url, class: 'main_img_in_admin_interface' ), admin_prize_path(prize), target: :blank ) }
            t.column("Name")              { |prize| link_to prize.prize_name, admin_prize_path(prize), target: :blank }
            t.column("Category")          { |prize| prize.prize_category }
            t.column("Initial quantity")  { |prize| prize.prize_initial_stock_quantity }

      end # end of Prize.each...

    end # end of panel "details of prizes"

和 PRIZE_TYPE 常量:

PRIZE_TYPES = ["Jackpot prize","Consolation prize", "awesome prize"]

您可以使用 ruby​​ 的復數形式:

prize_type.pluralize(count)
"Jackpot prize".pluralize(1)
#> Jackpot prize
"Jackpot prize".pluralize(2)
#> Jackpot prizes

或者ActiveSupport::Inflector.pluralize如果你想自己做檢查:

prize_type.pluralize
"Jackpot prize".pluralize
#> "Jackpot Prizes"

或者 rails 有復數形式,它使用組合Inflector和一些基本邏輯:

pluralize(count, prize_type)
pluralize(1, prize_type)
#> 1 Jackpot prize
pluralize(2, prize_type)
#> 2 Jackpot prizes

您可以使用 ruby​​ 實例方法

http://apidock.com/rails/ActionView/Helpers/TextHelper/pluralize

"string".pluralize(count)

所以對於你的情況,

prizes_count = deal.prizes.where(prize_type: u).count
h3 "The deal has #{prizes_count} #{u.pluralize(prizes_count)}"

使用pluralize

count = deal.prizes.where(:prize_type => u).count
h3 "The deal has #{count} #{u.pluralize(count)}}"

根據復數

你可以做

pluralize(1, 'person')
# => 1 person

pluralize(2, 'person')
# => 2 people

pluralize(3, 'person', plural: 'users')
# => 3 users

pluralize(0, 'person')
# => 0 people

pluralize(2, 'Person', locale: :de)
# => 2 Personen

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM