009994c3985985809d2d644bd49aa1c2

怎樣在 Cells Controller 中呼叫 helper

2011-12-05 18:14:30 +0800lulalalaRuby on Rails 節點 中發起
最後由 lulalala2011-12-07 17:01:04 +0800回應 , 373次閱讀

我在使用 cells 這個 gem ,現在想要在裡頭的 controller 呼叫一般的 helper (如 link_to),請問要怎樣作呢?我有試過

helper ActionView::Helpers::AssetTagHelper

可是這只能在 view 裡面使用,controller不行。

啊,還有請問有在 stack overflow 上積分高的人嗎,能否請你建個 rails-cells 之類的 tag ,因為目前標上 cell 的東西五花八樣,無法拿來作搜尋用。

截至 2011-12-07 17:01:04 +0800,共收到 6 條回應
19e786a2a74377ff6e052d87fd8d1fa8
xdite 1樓, 於2011-12-05 20:59:47 +0800回應

controller 裡面呼叫 helper 本來就是犯規行為吧。不鼓勵你這樣作。

另外如果硬要叫也不是不可以。我記得在 Rails 2.x 時代我是這樣呼叫的...不知道現在還可不可以。

直接用..

ApplicationController.helpers.buddy_icon(xxx)

009994c3985985809d2d644bd49aa1c2
lulalala 2樓, 於2011-12-05 22:53:29 +0800回應

主要是想學 draper 把 view 弄的更乾淨,因為有幾個 link_to 要重複些許複雜的邏輯,寫在view便是要兩個if(一個還在attribute裡面)。

謝謝我明天試試(我試了 http://api.rubyonrails.org/classes/ActionController/Helpers/ClassMethods.html#method-i-helpers 不過不成功,大概cell controller不算是真正的 controller)

19e786a2a74377ff6e052d87fd8d1fa8
xdite 3樓, 於2011-12-05 23:02:49 +0800回應

please don't use drapper .....

009994c3985985809d2d644bd49aa1c2
lulalala 4樓, 於2011-12-06 00:16:26 +0800回應

yar not using it, just wrapping built-in helper logic to keep it DRY

2b0e03ef8ff7fd827f57f53c79346bc3
chitsung 5樓, 於2011-12-06 12:52:44 +0800回應

試試…

code

class ACell < Cell::Base
helper ApplicationHelper
helper SomhingsHelper
helper Admin::AnothersHelper
...

code

009994c3985985809d2d644bd49aa1c2
lulalala 6樓, 於2011-12-07 17:01:03 +0800回應

最後找到說明了,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

需要 登入 後方可回應,如果你還沒有帳號按這裡 註冊