如何在 Rails 中创建对象时从 Postgres 计算函数中获取值 [英] How to get the value from Postgres computed function upon object creation in Rails

查看:21
本文介绍了如何在 Rails 中创建对象时从 Postgres 计算函数中获取值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

几个月前,我问了一个关于如何在创建之前按字母顺序递增字段值的问题.

A few months ago, I asked a question on how to increment the value of a field in alphabetical order in before create.

经过一些评论后,我们得出了一个非常不错的解决方案我现在需要扩展此解决方案,并且返回对象并在创建时将其显示在同一页面上.我需要 Ajax 来做到这一点.

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.

当前的问题是我不知道如何将创建的 setup_code 附加到创建时返回的 JSON 对象.

The current problem is I have no idea how to attach the created setup_code to the JSON object that is returned upon creation.

我尝试了以下方法:

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

我们的想法是能够立即访问data.exposure_setup_code,而无需重新加载页面.

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?

推荐答案

您链接到的解决方案是使用 PostgreSQL 函数为相关列提供默认值.这意味着在 SQL INSERT 期间应用默认值,该 SQL INSERT 在数据库中创建模型实例;这发生在 ActiveRecord 验证之后,所以 before_validation 为时过早,您希望在创建模型后立即重新加载模型.

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.

我想你想说:

after_create :reload # Make sure to load database-generated defaults.

这篇关于如何在 Rails 中创建对象时从 Postgres 计算函数中获取值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆