Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
474 views
in Technique[技术] by (71.8m points)

observers - 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?

question from:https://stackoverflow.com/questions/65948472/observe-rails-actiontext-for-changes

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...