Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
472 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 Reply

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...