[英]Helper methods for models in Rails
Rails中的模型是否有適當的輔助方法? 控制器和視圖有輔助方法,但我不確定放置模型輔助方法的最佳位置。 除了向ActiveRecord::Base
添加一個方法,我不想這樣做。
更新 :似乎憂慮很有意義。 這是我想要的一個例子。 某些模型永遠不會被刪除,所以我添加一個總是拋出異常的回調:
before_destroy :nope
def nope
raise 'Deleting not allowed'
end
有顧慮,我可以這樣做嗎?
class MyModel < ActiveRecord::Base
include Undeletable
end
module Undeletable
extend ActiveSupport::Concern
included do
before_destroy :nope
end
def nope
raise 'Deleting not allowed'
end
end
這是Rails這樣做的方式嗎?
如果要在model
使用helper_method my_helper_method
,可以編寫
ApplicationController.helpers.my_helper_method
如果您需要更多的靈活性,例如,如果您還需要覆蓋某些方法,則可以執行以下操作:
class HelperProxy < ActionView::Base
include ApplicationController.master_helper_module
def current_user
#let helpers act like we're a guest
nil
end
def self.instance
@instance ||= new
end
end
然后使用
HelperProxy.instance.my_helper_method
如果你有強烈的神經,你也可以嘗試將ApplicationController.master_helper_module
直接包含在你的model
。
via:makandracards的帖子。
供您參考: http : //railscasts.com/episodes/132-helpers-outside-views
如果您要問的是在rails 4.2中將多個模型共享的代碼放在何處,那么標准答案必須是使用問題: 如何在Rails 4中使用問題
但是,有一些很好的論據(例如這個 )只是使用標准的rails模塊包含,並且擴展為marek-lipka建議。
我強烈建議不要在模型中使用ApplicationController輔助方法,因為你將導入很多不必要的行李。 在我看來,這樣做通常是一種難聞的氣味,因為這意味着你沒有分離MVC元素,並且你的應用程序中存在太多的相互依賴性。
如果需要通過添加僅在視圖中使用的方法來修改模型對象,那么請查看裝飾器。 例如https://github.com/drapergem/draper
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.