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

Calling method from view in model on model instance, rails?

我的模型中有一个来自 rgrove sanitize 的 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>

我只是非常模糊地理解 instance/class 方法,但我知道我想在我认为的微博实例上调用我的方法。当我调用 self.gif_url 引用数据库中的原始对象然后 运行 我在实例上的方法时,我以为我已经在这样做了。

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

查看代码

_micropost.html.erb

....  
<%= sanitized_gif_url %> (I know this doesnt look right)
....

您已将 sanitized_gif_url 编写为实例方法,这意味着它必须在 Micropost class.

的实例上调用

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

然后在视图中这样修改你的内容: <%= @micropost.sanitized_gif_url %>

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

没有将方法显式传递给对象,它被传递给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 的模型。