0

The Contact model has default values for the column is_pickup

Contact.new
=> id: 2, email: nil, order_id: nil, is_pickup: true

Now i am connecting the contact table to the rails db views using scenic gem

class OrderContact < ApplicationRecord
      self.table_name = 'temp_contacts'
      self.primary_key = :id
    ...
end

The issue is that i am unable to set default values for the record.

i tried adding the following in the contact model

def is_pickup
  self[:is_pickup] || true
end

But still it is not showing up in the rails console

Contact.new
    => id: 2, email: nil, order_id: nil, is_pickup: nil

I need to set the default value when the record is initialised.

Any idea on how to set default values for the model when using db views?

prajeesh
  • 2,202
  • 6
  • 34
  • 59
  • If I understand correctly `Contact` points to the table (with correct defaults), and `OrderContact` points to the view. Why does `Contact` no longer have the defaults set? Are you trying to create a new contact on `OrderContact` ? You cannot create a new item on a view, you should always create it on the table (aka corresponding model). – nathanvda Jan 12 '21 at 17:31

1 Answers1

0

you can specify default value in migrations

change_column_default :contacts, :is_pickup, true

or you can add callback in your model

class Contact < ActiveRecord::Base
    after_initialize :init

    def init
      self.is_pickup ||= true
    end
  end    
bigidigi89
  • 63
  • 7