怎樣在 Cells Controller 中呼叫 helper
我在使用 cells 這個 gem ,現在想要在裡頭的 controller 呼叫一般的 helper (如 link_to),請問要怎樣作呢?我有試過
helper ActionView::Helpers::AssetTagHelper
可是這只能在 view 裡面使用,controller不行。
啊,還有請問有在 stack overflow 上積分高的人嗎,能否請你建個 rails-cells 之類的 tag ,因為目前標上 cell 的東西五花八樣,無法拿來作搜尋用。
controller 裡面呼叫 helper 本來就是犯規行為吧。不鼓勵你這樣作。
另外如果硬要叫也不是不可以。我記得在 Rails 2.x 時代我是這樣呼叫的...不知道現在還可不可以。
直接用..
ApplicationController.helpers.buddy_icon(xxx)
主要是想學 draper 把 view 弄的更乾淨,因為有幾個 link_to 要重複些許複雜的邏輯,寫在view便是要兩個if(一個還在attribute裡面)。
謝謝我明天試試(我試了 http://api.rubyonrails.org/classes/ActionController/Helpers/ClassMethods.html#method-i-helpers 不過不成功,大概cell controller不算是真正的 controller)
please don't use drapper .....
yar not using it, just wrapping built-in helper logic to keep it DRY
試試…
code
class ACell < Cell::Base
helper ApplicationHelper
helper SomhingsHelper
helper Admin::AnothersHelper
...
code
最後找到說明了,helper 方法讓 module 能讓 view 用到,但是不能被 controller 用到。
要讓 controller 用到,得用 include 還得加一個 controller 方法避免「undefined local variable or method `controller' 」問題(不知道原因)。範例程式碼請看最下方:
而且我發現要是用 image_tag 指定到 asset 圖片時,在 cell 中呼叫反而不會從 images/ 轉換到 assets/ ,所以會破圖。
總而言之問題多多,所以決定不這樣用,還是寫在view中。
include ActionView::Helpers::AssetTagHelper
def star
image_tag("star-#{@rating}.png", alt:"#{@rating}-Star")
end
def controller
parent_controller
end
helper_method :star