简体   繁体   English

Ruby on Rails-创建记录后设置属性

[英]Ruby on Rails - set attribute after record was created

I'm using activeadmin in my RoR webapp. 我在RoR Web应用程序中使用activeadmin。 when I create a new user/record, I want to set/update an attribute depend on it's id/pk. 创建新用户/记录时,我想根据其ID / pk设置/更新属性。 eg his id is 1234, column X should have the value 1234-XXX. 例如,他的ID为1234,则X列的值应为1234-XXX。

Since there is no activerecord callback for that(i cant set the value with callbacks, because there isnt one, after the entry is created/stored in the db) you to ask, how I could solve this? 由于没有为此的activerecord回调(我无法使用回调设置值,因为没有一个,在条目创建/存储在数据库中之后),我想问如何解决这个问题?

Thanks in advance 提前致谢

You can use the after_action controller callback : 您可以使用after_action控制器回调:

class RecordsController < ApplicationController
  after_action :set_columnx, only: [:create, :update]

  private
  def set_columnx
    @record = Record.find(params[:id])
    @record.columnx = "#{@record.id}-ABCD"
    @record.save!
  end
end

I think you can use after_commit callback 我认为您可以使用after_commit回调

after_commit :do_something, on: :create

def do_something
  update_column(:column_x, "#{id}-XXX")
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM