代码之家  ›  专栏  ›  技术社区  ›  Lee Eather

在模型实例rails上从模型中的视图调用方法?

  •  0
  • Lee Eather  · 技术社区  · 9 年前

    我的模型中有一个来自rgrove sanitize gem的清理方法

    Micropost
      belongs_to :user
    
      def sanitized_gif_url
        self.gif_url = Sanitize.fragment(micropost.gif_url, elements etc to sanitize here).html_safe
      end
    

    sanitized_gif_url 在我的微观观点中,但当我使用此代码时,我得到 undefined local variable or method sanitized_gif_url' for #<#<Class:0xb886cf0>

    我对实例/类方法的理解非常模糊,但我知道在我看来,我想在我的micropost实例上调用我的方法。我打电话的时候以为我已经在做了 self.gif_url 引用数据库中的原始对象,然后在实例上运行我的方法。

    **编辑: gif_url 是我要清理的属性。

    查看代码

    _微孔。html。erb公司

    ....  
    <%= sanitized_gif_url %> (I know this doesnt look right)
    ....
    
    2 回复  |  直到 9 年前
        1
  •  1
  •   EJAg    9 年前

    在不将方法显式传递给对象的情况下,它被传递给 self ,在视图中表示视图实例。因此,您需要将方法传递给Micropost实例(例如。 @micropost.sanitized_gif_url

    ##Micropost.rb
    ##micropost in micropost.gif_url is undefined. you can use self.gif_url or just gif_url, as self is implied. 
    ##I'd remove "self.gif_url =" too unless this is used in a callback to sanitize url before saving
      def sanitized_gif_url
        self.gif_url = Sanitize.fragment(gif_url, elements etc to sanitize here).html_safe
      end
    

    然而,如果这样做的目的是在视图中显示一个经过清理的方法,我建议您创建一个视图辅助对象,而不是Micropost的方法。

    ##helpers/application_helper.rb
    def sanitized_gif_url(url)
      Sanitize.fragment(url, elements etc to sanitize here).html_safe
    end
    
    ## _micropost.html.erb
    <%= sanitized_gif_url(@micropost.gif_url) %>
    

    #sanitized_gif_url 关于Micropost的具体实现。因此,您可以将此方法用于任何其他URL或具有要清理的URL的模型。

        2
  •  1
  •   abax    9 年前

    你已经写了你的 sanitized_gif_url 作为实例方法,意味着必须在 Micropost 班

    您所说的视图的控制器应该设置 微孔 实例作为视图访问的实例变量。类似于 @micropost = Micropost.find(params[:id]) (获取 微孔 您正在视图中使用)

    <%= @micropost.sanitized_gif_url %>

    在类的一个实例上调用实例方法。类方法在类本身上调用。