问题
A few months ago, I asked a question on how to increment the value of a field in alphabetical order in before create.
After a few comments, we arrived at a very nice solution I currently have the requirement to extend this solution now and return the object and display it on the same page upon creation. I need Ajax to do this.
The current problem is I have no idea how to attach the created setup_code to the JSON object that is returned upon creation.
I have tried the following:
before_validation :find_setup_code, on: :create
def find_setup_code
self.reload
end
def exposure_setup_code
self.setup_code
end
def as_json(options)
super(methods: %i[exposure_setup_code])
end
The idea is to be able to have access to data.exposure_setup_code
immediately the object is created without having to reload the page.
What is the right way to approach this?
回答1:
The solution you link to is using a PostgreSQL function to supply the default value for the column in question. That means that the default is be applied during the SQL INSERT which creates your model instance in the database; that happens after the ActiveRecord validations so before_validation
is too soon, you want the reload the model immediately after you've created it.
I think you want to say:
after_create :reload # Make sure to load database-generated defaults.
来源:https://stackoverflow.com/questions/54355381/how-to-get-the-value-from-postgres-computed-function-upon-object-creation-in-rai