2014-07-16 34 views
0

我只是在学习ruby,并且想要练习编写rails的小帮手方法,作为修改基础知识的好方法。 我想要做的就是为范围对象提供一个计数器。简单的ruby方法帮手

所以在我看来,我写这篇文章

=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 

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

+0

你在你的application_helper.rb文件或模型写这个? – Edmund

+0

应用帮手 –

+0

你能粘贴确切的错误吗?如果它在你的应用程序帮手中,它应该工作 – Edmund

回答

4

可以使用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) 
+0

你也可以通过批发方式传递方法名:'Photo.send(state).count'然后'stats_counter_for(:with_active_state)'。 – tadman

+0

是的,我知道,但我认为如果在视图中频繁使用它会太重复。 – backpackerhh

+0

是的,我更喜欢你的方法,但只是提到一个更通用的解决方案。 – tadman