0

Rails 的pluralize方法没有像我想要的那样工作(单词不是英文),所以我开始尝试自己的解决方案。我开始使用这种方法很简单ApplicationController

def inflect(number, word)
  if number.to_i > 1
    word = word + "s"
  end      
  return "#{number} #{word}"
end

在我看来,这样称呼它:

<% @articles.each do |article| %>
  <%= inflect(article.word_count, "word") %>
  <%= inflect(article.paragraph_count, "paragraph") %>
  ...
<% end %>

但这让我:

undefined method `inflect' for #<#<Class:0x3ea79f8>:0x3b07498>

当我认为它应该只是一个整数时,我发现它引用了一个成熟的对象很奇怪,所以我在控制台上对其进行了测试:

article = Article.first
=> (object hash)
article.word_count
=> 10
article.word_count.is_a?(Integer)
=> true

所以我抛出了一个 quick words = article.word_count.to_i,但它并没有抛出 TypeError,它实际上什么也没做,并且仍然返回相同的错误:undefined method ``inflect' for #<#<Class:0x3ea79f8>:0x3b07498>引用该`inflect(article.word_count, "word")行。

然后我想可能inflect已经是一个 Rails 方法并且它是某种命名冲突,但不管我将方法的名称更改为什么,它总是给我同样的错误:undefined method ``whatever' for #<#<Class:0x3ea79f8>:0x3b07498>

然后我在控制台上对其进行了测试,它运行良好。这是怎么回事?

4

1 回答 1

1

Put your inflect method in ApplicationHelper, not ApplicationController

by default all code in your helpers are mixed into the views

the view is its own entity, it is not part of the controller, when a view instance gets created (automatically when your controller action executes) it gets passed any instance variables you define in your controller action, but does not have access to controller methods directly

NOTE: you can define methods in your controller to expose them to your views by using the helper_method macro - see this post for more info on that - Controller helper_method

but in general you would define the view helper methods in the helpers classes and not in the controller

于 2013-02-18T02:32:25.357 回答