简体   繁体   中英

How to set values in rails without form field

We have an field in the Database which should be set automatic as an UUID String. how do we that. the view doesn't contain this field because it will be autogenerated. Our new-form will called so.

def new
  @list = List.new
  respond_to do |format|
      format.html
end

Our create-action is here

def create
  @list = List.new(params[:list])
  @list = list.create!(params[:list]) 
end

If we try this

@list.admin_key = UUIDTools::UUID.timestamp_create().to_s

we get an validation error and the field is empty. the controller require

require 'uuidtools'

Our validation for the field is that is prencense and unique

validates :admin_key,
            :presence => true,
            :uniqueness => true

How did we get the admin_key into the database?

u have to do this in your model

before_validation(:on => :create) do
  self.admin_key = UUIDTools::UUID.timestamp_create().to_s
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM