Ruby on Rails - concatenate strings on save to database upon user clicking create action

混江龙づ霸主 提交于 2019-12-06 15:16:02

问题


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

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.

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

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


回答1:


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


来源:https://stackoverflow.com/questions/6793045/ruby-on-rails-concatenate-strings-on-save-to-database-upon-user-clicking-creat

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