[英]How to create/save this database special calculated field - RoR
I have a database field
called sample_code . 我有一个名为sample_code的database field
。 This field is composed on the following way: sample_id/year/lab_id
该字段通过以下方式组成: sample_id/year/lab_id
The lab_id
is fixed, always the same. lab_id
是固定的,始终相同。 The year
changes accordingly to the current year... The sample_id
its incremental (resetting every year and not a database field). year
将相应地更改为当前年份... sample_id
的增量(每年重置,而不是数据库字段)。
What I want to do is every-time I create a new sample it generates this sample_code
for me and saves it along with the rest of the sample fields... 我想做的是每次创建一个新样本时,它sample_code
为我生成此sample_code
并将其与其余样本字段一起保存...
My doubts are: 1 - How can I keep incrementing sample_id if it's not on the database? 我的疑问是:1-如果sample_id不在数据库中,该如何继续递增? 2 - How can I reset the sample ID code each year? 2-每年如何重置示例ID代码? 3 - Where's the best place to put/call this code? 3-放置/调用此代码的最佳位置是哪里? Sample's controller? 样品的控制器?
Thanks for all the help you can give 感谢您提供的所有帮助
If you're not using your database outside of your app, it should be fine to just store the sample_id
as its own column. 如果您不在应用程序外部使用数据库,则最好将sample_id
存储为自己的列。 You can then put a method on your model that returns something like: 然后,您可以在模型上放置一个返回如下内容的方法:
def sample_code
"#{sample_id}/#{Time.now.year}/<lab_id>"
end
Then you can just increment sample_id
each time. 然后,您只需每次增加sample_id
。
EDIT 编辑
Since you need to reset the id to 1 each year and the model is called Sample
, you should avoid confusion by calling it something like annual_id
instead of sample_id
. 由于您需要每年将id重置为1,并且该模型称为Sample
,因此应通过将其annual_id
为annual_id
而不是sample_id
来避免混淆。 sample_id
would likely be confused with sample.id
, which is a completely different thing. sample_id
可能会与sample.id
混淆,这是完全不同的事情。
With that change, you should just store the info in three columns on the model to make it easy: annual_id
, year
, and lab_id
. 进行此更改后,您应该将信息存储在模型的三列中以使其变得容易: annual_id
, year
和lab_id
。 Then for each record you can set: 然后可以为每个记录设置:
annual_id = Sample.where(year: Time.now.year).pluck(:annual_id).max.to_i + 1
year = Time.now.year
lab_id = <however you are defining this>
This will use the current year for year
and then reset the annual_id
to 1 when there are no records because the year has changed (new year will give nil.to_i + 1 => 1
). 这将使用当前年份作为year
,然后在由于年份更改而没有记录的情况下将annual_id
重置为1(新年份将为nil.to_i + 1 => 1
)。
Then you can just return the format you want for any given data point: 然后,您可以返回任何给定数据点所需的格式:
def sample_code
"#{annual_id}/#{year}/#{lab_id}"
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.