Aipack
Aipack

Reputation: 94

How to save user ID who edited the record - Rails

I want to save the user ID who edited the article on my aplication. I'm using Devise gem.

here's the update method in article controller

def update
    @article = Article.find(params[:id])
    updated = @article.update(article_params) do |article|
      article.editor_id = current_user.id
    end

    if updated
      format.html { redirect_to @article, notice: 'Article was successfully updated.' }
      format.json { render :show, status: :ok, location: @article }
    else
      format.html { render :edit }.s: :unprocessable_entity }
    end
end

update process is success but it didn't save the user id. And plus, how to save the user id only if the article content changed? Any advice?

Upvotes: 0

Views: 760

Answers (3)

I think you should check out act as versioned: https://github.com/technoweenie/acts_as_versioned

The other way is that you create another model for it, which will logs the changes, and who did them. Like ArticleLog (article_id, user_id, changed_attr, prev_val).

Write a hook to create ArticleLog on update of Article, if the attribute you want to log is changed.

https://guides.rubyonrails.org/active_record_callbacks.html#updating-an-object

I hope I helped you! :)

Upvotes: 0

Aipack
Aipack

Reputation: 94

with direction from @sujan i change my code to this. i'm removing the update variable to make it more simpler

   def update

        @article.assign_attributes(article_params)   

        if  @article.content_changed?
           @article.editor_id = current_user.id    
        end

        respond_to do |format|
          if @article.save
            format.html { redirect_to @article, notice: "Article succesfully updated" }
            format.json { render :show, status: :ok, location: @article }
          else
            format.html { render :edit }
            format.json { render json: @article.errors, status: :unprocessable_entity }
          end
        end

Upvotes: 1

Sujan Adiga
Sujan Adiga

Reputation: 1371

You need to save the article after assigning the editor_id. Try,

updated = @article.update(article_params) do |article|
  article.editor_id = current_user.id
  article.save
end

or better,

updated = false
@article.assign_attributes(article_params)
if @article.changed?
  @article.editor_id = current_user.id
  updated = @article.save
end

This will update the article only if there are changes.

Refs:

  1. assign_attributes
  2. changed

Upvotes: 0

Related Questions