[英]Ruby: How to pluralize/singularize a word in Active Admin panel according to variable quantity (Active Admin, rails 3.2, ruby)
I'ma newbie in Ruby on Rails and I don't manage to change the end of a word according to the quantity it has.我是 Ruby on Rails 的新手,我无法根据单词的数量更改单词的结尾。
Near top of the code below, you'll see that I write在下面代码的顶部附近,你会看到我写的
h3 "The deal has #{deal.prizes.where(:prize_type => u).count} #{u}
The "u" here takes one of the value inside an array called PRIZE_TYPE.此处的“u”采用名为 PRIZE_TYPE 的数组中的值之一。 How can I do so that
我怎么能这样做
if count= 1, it displays "the deal has 1 jackpot prize"如果count= 1,则显示“这笔交易有1个头奖”
if count=4, it displays "the deal has 4 jackpot prizeS如果count=4,则显示“这笔交易有4个头奖
Note: The count can't be = 0 or < 0注意:计数不能为 = 0 或 < 0
Here is my code:这是我的代码:
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"
And the PRIZE_TYPE constant:和 PRIZE_TYPE 常量:
PRIZE_TYPES = ["Jackpot prize","Consolation prize", "awesome prize"]
You could use ruby's pluralize:您可以使用 ruby 的复数形式:
prize_type.pluralize(count)
"Jackpot prize".pluralize(1)
#> Jackpot prize
"Jackpot prize".pluralize(2)
#> Jackpot prizes
Or ActiveSupport::Inflector.pluralize if you want to do the check yourself:或者ActiveSupport::Inflector.pluralize如果你想自己做检查:
prize_type.pluralize
"Jackpot prize".pluralize
#> "Jackpot Prizes"
Or rails has pluralize that uses a combination Inflector and some base logic:或者 rails 有复数形式,它使用组合Inflector和一些基本逻辑:
pluralize(count, prize_type)
pluralize(1, prize_type)
#> 1 Jackpot prize
pluralize(2, prize_type)
#> 2 Jackpot prizes
you can use the ruby instance method您可以使用 ruby 实例方法
http://apidock.com/rails/ActionView/Helpers/TextHelper/pluralize http://apidock.com/rails/ActionView/Helpers/TextHelper/pluralize
"string".pluralize(count)
so for your case,所以对于你的情况,
prizes_count = deal.prizes.where(prize_type: u).count
h3 "The deal has #{prizes_count} #{u.pluralize(prizes_count)}"
Use pluralize
使用
pluralize
count = deal.prizes.where(:prize_type => u).count
h3 "The deal has #{count} #{u.pluralize(count)}}"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.