【问题标题】:Observe Rails ActionText for changes观察 Rails ActionText 的变化
【发布时间】:2021-05-03 00:26:55
【问题描述】:

观察 Rails ActionText 变化的最简单方法是什么?我的用例是在编辑富文本字段时发送通知。

由于 ActionText 创建了与模型的关联,而不是模型上的属性,因此脏模块不可用。

我可以使用自定义脏关联模块,例如:https://anti-pattern.com/dirty-associations-with-activerecord

我还可以在模型上有一个属性,它会在每次更新时保存 ActionText::Content 纯文本,然后进行观察。

还有其他选择吗?

【问题讨论】:

    标签: ruby-on-rails observers actiontext


    【解决方案1】:

    你可以像下面这样使用hash

    class ArticlesController < ApplicationController
      
      ...
    
      def update
        @article = Article.find(params[:id])
        orig_content_hash = @article.content.to_s.hash
    
        if @article.update(article_params)
          # hash will have changed if content was updated
          send_notification unless @article.content.to_s.hash == orig_content_hash
          redirect_to article_path(@article.id)
        else
          render :edit
        end
      end
    
      ...
    
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-08-05
      • 2010-11-09
      • 2018-02-26
      • 2015-09-13
      • 1970-01-01
      • 2020-07-29
      • 1970-01-01
      • 2021-08-30
      相关资源
      最近更新 更多