Ruby on Rails - 在用户单击创建操作时连接保存到数据库的字符串 [英] Ruby on Rails - concatenate strings on save to database upon user clicking create action

查看:51
本文介绍了Ruby on Rails - 在用户单击创建操作时连接保存到数据库的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

很晚了,我可能应该睡在这个上面.简单的

Its late and I probably should sleep on this. Easy one

我在用户填写的表单中有 3 个字段.一旦他们单击创建按钮,这些记录就会保存到数据库中.简单.

I have 3 fields in a form which a user fills in. Once they click the create button these records are saved to the database. Simple.

但是我希望将这三个字段中的数据同时连接在一起,没什么特别的……并与其他记录同时插入到数据库中.这应该会在用户创建后反映给显示页面上的用户.

However I want the data from these three fields at the same time to be concatenated together, nothing fancy..and inserted to the database at the same time as the other records. This should reflect back to the user on the show page after they create.

所以我需要一个操作来连接 3 个 db 列,比如列名是名字、姓氏和 DOB.表名 PeopleDetails

So I need an action to concatenate 3 db columns lets say column names are firstname, surname and DOB. table name PeopleDetails

我尝试使用模型中内置的 after_create、before_save 来构建模型,但是 nada.建议.我想我会在睡一觉后回来重温这个

I have tried building the model using after_create, before_save, built into the model, but nada. suggestions. I think I will come back and revisit this after some sleep

推荐答案

假设您有一个名为 full_name 的列(模型属性),那么您可以通过以下方式将所有内容组合在一起创建/保存模型:

Assuming you have a column (model attribute) called full_name than you can combine all together on a model create/save via:

class User < ActiveRecord::Base
  before_save :concatenate_details

  def concatenate_details
     self.full_name = "#{firstname} #{surname} #{dob}"
  end

end

这篇关于Ruby on Rails - 在用户单击创建操作时连接保存到数据库的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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