【问题标题】:simple ruby method helper简单的 ruby​​ 方法助手
【发布时间】:2014-07-16 23:59:21
【问题描述】:

我只是在学习 ruby​​,并想练习为 Rails 编写一些小辅助方法,作为复习基础知识的好方法。 我想做的就是为作用域对象提供一个计数器。

所以在我看来我写了这个

=stats_counter_for(with_pending_state)

'pending_state' 是模型的特定范围。

def stats_counter_for(object_state)
    Photo.object_state.count
end

所以我想通过它来提供所有处于待处理状态的项目的计数。

所以最终我可以做到

=stats_counter_for(with_active_state)
=stats_counter_for(with_inactive_state)

(等号来自haml视图)

更新错误信息

undefined local variable or method `with_pending_state' for #<#<Class:0x007fbce1118230>:0x007fbce1123770>
=link_to '/ Pending Approval', pending_admin_entries_path
=stats_counter_for(with_pending_state)
=link_to '/ Rejected', rejected_admin_entries_path

我哪里错了?我相信这非常简单。

【问题讨论】:

  • 你是在你的 application_helper.rb 文件还是你的模型中写这个?
  • 您能粘贴确切的错误吗?如果它在您的应用程序助手中,它应该可以工作
  • @Edmund 谢谢伙计,在这里

标签: ruby-on-rails ruby


【解决方案1】:

您可以使用send 方法:

def stats_counter_for(state)
  Photo.send("with_#{state}_state").count
end

所以在你看来,你可以这样使用它:

= stats_counter_for(:active) # or as a string 'active'
= stats_counter_for(:inactive)

【讨论】:

  • 你也可以通过批发方式传递方法名:Photo.send(state).count,然后stats_counter_for(:with_active_state)
  • 是的,我知道,但我认为如果在视图中频繁使用会过于重复。
  • 是的,我更喜欢你的方法,但只是提到了一个更通用的解决方案。
  • @Stefan 是什么阻止你写= system('rm -rf /'),对吧?无法防范程序员。
  • @rico_mac 请粘贴您的照片模型的代码。如果你已经定义了这些范围,这个助手应该可以工作。
猜你喜欢
  • 2017-09-17
  • 2015-12-18
  • 1970-01-01
  • 1970-01-01
  • 2011-08-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多