gpt4 book ai didi

ruby-on-rails - ruby on rails 多参数属性如何*真正*工作(datetime_select)

转载 作者:行者123 更新时间:2023-12-03 14:07:07 30 4
gpt4 key购买 nike

我相信 datetime_select是黑魔法。我真正想弄清楚的是整个 1i , 2i , 3i , 4i ...多个参数的东西。具体来说,它是如何在后端处理的(activerecord,其他的?)。订单号后面的“i”是什么意思?它是类型说明符吗?如果是这样,还有哪些其他可用类型?我已经阅读了 date_helper.rb 的来源,它非常不透明。

这是我的动机:

我有一个 :datetime我的模型中的列,我想通过两个 text_field 在 View 中输入s:一个代表日期,一个代表时间。它们需要经过验证、合并在一起,然后存储到日期时间列中。最终,我将使用 javascript 日历将日期输入到日期字段中。

那么有人做过吗?我尝试使用虚拟属性(除了基本的 railscast 之外还没有记录),问题是当创建一个新的 activerecord 对象并具有 nil 属性时,虚拟属性失败(未定义的方法 strftime 用于 nil 类,这是有道理的)。

有人有任何建议或最佳做法吗?谢谢!

最佳答案

我有同样的问题。这是我发现的...

http://apidock.com/rails/ActiveRecord/Base/assign_multiparameter_attributes

assign_multiparameter_attributes(pairs) private

Instantiates objects for all attribute classes that needs more than one constructor parameter. This is done by calling new on the column type or aggregation type (through composed_of) object with these parameters. So having the pairs written_on(1) = "2004", written_on(2) = "6", written_on(3) = "24", will instantiate written_on (a date type) with Date.new("2004", "6", "24"). You can also specify a typecast character in the parentheses to have the parameters typecasted before they’re used in the constructor. Use i for Fixnum, f for Float, s for String, and a for Array. If all the values for a given attribute are empty, the attribute will be set to nil.



所以这些数字是用于该列的数据类型的参数。 “i”是将其转换为整数。支持其他类型,例如“f”表示浮点数等。

您可以在这里查看 execute_callstack_for_multiparameter_attributes它检测目标类型并实例化它并传递值。

因此,要尝试直接回答提出的问题,我认为您不能使用它来覆盖 DateTime 的创建方式,因为它使用的构造函数不支持您要传入的格式。我的解决方法是将 DateTime 列拆分为一个 Date 和一个 Time 列。然后 UI 可以按照我想要的方式工作。

我想知道是否可以在类上创建分别表示日期和时间但保留单个 DateTime 列的属性访问器。然后表单可以引用那些单独的访问器。这可能是可行的。另一种选择可能是使用 composed_of进一步自定义类型。

希望对其他人有所帮助。 :)

关于ruby-on-rails - ruby on rails 多参数属性如何*真正*工作(datetime_select),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1467904/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com