Zin*_*inc 32 ruby-on-rails ruby-on-rails-3
我是Rails的新手,只是想知道何时将代码放入Helper而不是将代码放入模型中.
有一个"经验法则"可以这么说吗?
Chu*_*ron 27
如果您在视图(模板)中工作,则需要使用帮助程序,并且需要构建一个复杂的HTML,例如a <table>.或者,如果要更改某些未连接到数据库的演示数据.
def truncate_html( html, options = {} )
options[:length] = 35 unless options[:length]
truncate( strip_tags( html ), options )
end
Run Code Online (Sandbox Code Playgroud)
在使用数据库对象时使用模型,并且希望简化业务逻辑.
def one_day?
start_date.to_s[0,9] == end_date.to_s[0,9]
end
Run Code Online (Sandbox Code Playgroud)
以下是指南中的助手:http://guides.rubyonrails.org/form_helpers.html
这里是模型:http://guides.rubyonrails.org/active_record_querying.html
当帮助程序创建的代码仅在视图中显示时,最好使用帮助程序.例如,如果您想要有帮助创建HTML链接的方法,那么它们应该放在帮助器中:
def easy_link user
link_to(user.name, user)
end
Run Code Online (Sandbox Code Playgroud)
如果您的代码是业务逻辑,那么它应该放在您的模型中.您还应该在模型中放置尽可能多的业务逻辑,不要在视图和控制器中使用此代码.例如,如果要处理订单,该代码应该放在模型中:
def process
raise NotReadyToProcess unless ready_to_process?
raise NotValidPaymentDetails unless valid_payment_details?
process_payment
end
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
12677 次 |
| 最近记录: |