2

I'm using activeadmin in my RoR webapp. when I create a new user/record, I want to set/update an attribute depend on it's id/pk. e.g his id is 1234, column X should have the value 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?

Thanks in advance

  • 1
    `after_create` `after_update` or `after_save` can do the job. As their names say, the callback runs after the action (create/update), so the record is already saved in the db. – Sovalina May 06 '18 at 15:26
  • actually it doesnt work. – SmackerJacker May 06 '18 at 15:28
  • what is XXX in 1234-XXX? and what DB you use? – Stanislav Kr. May 06 '18 at 15:43
  • postgresql: so I want to create a new user. the person who creates it in the form fills out name,birthday etc. Then there is a hiddenfield, wich has to have the userid in it(pk - autoincrement) and then a string. I tried every call back,but I don't think that I am able to get the userid, because it is not persisted yet(am I wrong?) :after_create def bla(..) self.column = self.userid plus some string. If I look at the rails console,it's empty since it doesn't know the userid yet – SmackerJacker May 06 '18 at 15:49
  • Why would you repeat the id in a field. That seems peculiar to me. – jvillian May 06 '18 at 16:05
  • 1
    in my db:a person has a bankaccount. for a SEPA/direct debit initiation, people get a mandateid/reference. that's a string u have to create for every person( a string with i think 30 chars). you can define it urown rule for that. since names and stuff aren't unique, we take the userid and the date when it was created :) – SmackerJacker May 06 '18 at 16:15

2 Answers2

2

I think you can use after_commit callback

after_commit :do_something, on: :create

def do_something
  update_column(:column_x, "#{id}-XXX")
end
dan1d
  • 151
  • 1
  • 4
1

You can use the after_action controller callback :

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
Sovalina
  • 5,410
  • 4
  • 22
  • 39