haroldus
haroldus

Reputation: 131

Observe Rails ActionText for changes

What is the simplest way to observe Rails ActionText for changes? My use case is to send a notification when a rich text field has been edited.

Because ActionText creates an association to a model and is not an attribute on the model the Dirty module is unavailable.

I could use a custom dirty associations module, e.g.: https://anti-pattern.com/dirty-associations-with-activerecord

I could also have an attribute on the model which saves the ActionText::Content plain text every update and is then observed.

Are there any other options?

Upvotes: 1

Views: 576

Answers (1)

obiruby
obiruby

Reputation: 419

You could use hash like in the following

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

Upvotes: 1

Related Questions