Extend database models

Most of main DRG CMS database models are defined as concerns so they can be extended if required. Most of them also lack validation logic. Because what might be important for some implementation it might be irrelevant to other. That doesn't mean that it can't be changed. You can always extend basic models with additional fields, methods and controls.

 

In our example we will add two fields to DcUser model. Additional fields will hold data about membership in the club and club member card number. Lets look at newly created dc_user.rb.

 

class DcUser
include DcUserConcern


Followed by class declaration and inserting default DcUser code by including DcUserConcern.
 

field :member,      type: Boolean,  default: false
field :card_number, type: String

index( { 'card_number' => 1 } )

 

Followed by new fields declaration and additional index added to  model definition.

 

validate :my_control

def my_control
  if member and card_number.to_s.size < 8
    errors.add(:card_number, "Card number is not valid!")
  end
end

 

At the end additional validation is added to our model. We can do all our custom validation here.

 

Now that we have updated model we will update form for editing document. We may create new form, copy data from original form and add additional fields to it. Instead we will extend original form and add additional fields to newly created form. Since forms are loaded in reversed order of loading gems, forms with same name which are defined later are loaded first. 

 

extend: drg_cms.dc_user
form:
  tabs:
    tab2:
      10:
        name: member
        type: check_box
      20:
        name: card_number
        type: text_field

 

In first line we set that we are extending dc_user form defined in drg_cms gem. Our new fields will be added to new tab named tab2.

 

At last we add descriptions of our newly created fields to localization data. This is recommended way to supply labels and helper text for data entry fields. 

 

en:
  helpers:
    label:
      dc_user:
        tab2: Membership
        member: Is member
        card_number: Card number

    help:
      dc_user:
        member: User is member of our organization
        card_number: Membership card number

 

And if required we provide translations in additional file. Here is for example slovenian translation:

 

sl:
  helpers:
    label:
      dc_user:
        tab2: Članstvo
        member: Je član
        card_number: Številka kartice

    help:
      dc_user:
        member: Uporabnik je naš član
        card_number: Številka članske kartice

 

 


Last update: 24.01.2022