How to get the value from Postgres computed function upon object creation in Rails

瘦欲@ 提交于 2020-02-07 03:46:11

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!