如何保存编辑记录的用户 ID - Rails



我想保存在我的应用程序上编辑文章的用户ID。我正在使用设计宝石。

这是文章控制器中的更新方法

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

更新过程成功,但它没有保存用户 ID。另外,如何仅在文章内容更改时才保存用户ID?有什么建议吗?

来自@sujan的方向 我将代码更改为此。 我正在删除更新变量以使其更简单

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

您需要在分配editor_id后保存文章。 尝试,

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

或者更好,

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

仅当有更改时,才会更新文章。

裁判:

  1. assign_attributes
  2. 改变

我认为您应该查看按版本执行:https://github.com/technoweenie/acts_as_versioned

另一种方法是为它创建另一个模型,该模型将记录更改以及谁执行了这些更改。比如ArticleLog(article_id,user_id,changed_attr,prev_val(。

编写一个钩子以在更新文章时创建文章日志,如果要记录的属性已更改。

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

我希望我能帮助你! :)

最新更新