rails 3: is there a way to use pluralize() inside

2019-03-09 08:03发布

It seems pluralize() only works within a view -- is there some way that my models can use pluralize() too?

(I have methods in my model that return message strings for users that do not go to a view -- for example messages sent via SMS text message.)

5条回答
贼婆χ
2楼-- · 2019-03-09 08:13

Add this to your model:

include ActionView::Helpers::TextHelper
查看更多
爷的心禁止访问
3楼-- · 2019-03-09 08:13

This worked for me in rails 5.1 (see 2nd method, first method is calling it.)

# gets a count of the users certifications, if they have any.
def certifications_count
  @certifications_count = self.certifications.count
  unless @certifications_count == 0 
    return pluralize_it(@certifications_count, "certification")
  end
end

# custom helper method to pluralize.
def pluralize_it(count, string)
  return ActionController::Base.helpers.pluralize(count, string)
end
查看更多
淡お忘
4楼-- · 2019-03-09 08:21

YOu can add a method like this in your model

  def self.pluralize(word)
    ActiveSupport::Inflector.pluralize(word)
  end

and call it in this way

City.pluralize("ruby")
=> "rubies"
查看更多
Explosion°爆炸
5楼-- · 2019-03-09 08:26

My favorite way is to create a TextHelper in my app that provides these as class methods for use in my model:

app/helpers/text_helper.rb

module TextHelper                       
  extend ActionView::Helpers::TextHelper
end                                     

app/models/any_model.rb

def validate_something
  ...
  errors.add(:base, "#{TextHelper.pluralize(count, 'things')} are missing")
end

Including ActionView::Helpers::TextHelper in your models works, but you also litter up your model with lots of helper methods that don't need to be there.

It's also not nearly as clear where the pluralize method came from in your model. This method makes it explicit - TextHelper.pluralize.

Finally, you won't have to add an include to every model that wants to pluralize something; you can just call it on TextHelper directly.

查看更多
闹够了就滚
6楼-- · 2019-03-09 08:31

Rather than extend things, I just it like this:

ActionController::Base.helpers.pluralize(count, 'mystring')

Hope this helps someone else!

查看更多
登录 后发表回答