何时使用助手 vs 模型 [英] When to use Helpers vs Model

查看:51
本文介绍了何时使用助手 vs 模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Rails 的新手,只是想知道什么时候应该将代码放入 Helper 而不是将代码放入模型中.

I'm new to Rails and just wondering when I should put code into a Helper as opposed to putting the code into the Model.

是否有经验法则"可以这么说?

Is there a 'rule of thumb' so to speak for this?

推荐答案

如果您在视图(模板)中工作并且需要构建一些复杂的 HTML,例如

,请使用帮助程序..或者,如果您想更改一些未连接到数据库的演示数据.

Use helpers if you're working in a view (template) and you need to build a complex bit of HTML such as a <table>. Or, if you want to change some presentation data that's not connected to the database.

def truncate_html( html, options = {} )
  options[:length] = 35 unless options[:length]
  truncate( strip_tags( html ), options )
end

在处理数据库对象并且想要简化业务逻辑时使用模型.

Use models when you're working with database objects, and you want to simplify the business logic.

  def one_day?
    start_date.to_s[0,9] == end_date.to_s[0,9]
  end  

以下是指南中的 Helpers:http://guides.rubyonrails.org/form_helpers.html

这里是模型:http://guides.rubyonrails.org/active_record_querying.html

这篇关于何时使用助手 vs 模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆