← Back to Upcase

Why can't I call a method to set a db column during initialize?


(Roneesh Vashisht) #1

Hi all, I have a class called “Guest” in my rails app. There is a form used to create the guest object that takes a virtual attribute along with it called employee_name (this is not in the db). I want to use employee name to try and find if there’s a matching employee id in the db, if not, then guest should initialize with it’s employee_id column as nil. If there is, then the guest.employee_id gets set as that id.

class Guest < ActiveRecord::Base   
  belongs_to :organization

  attr_accessor :employee_name

  def initialize(params = {})
    @employee_name = params[:employee_name] || nil
    super #without call to super guest object doesn't initialize   
  end

  # Not part of this issue   
   def run_notification_service
        notification = Notification.new(self)
        notification.send   
   end
    
  def set_id
    self.employee_id = employee   
  end

  def employee
    Employee.find_by_name(@employee_name).try(:id)   
  end




end

Right now I can set my guest object’s employee_id when I call set_id in rails console.

But if I try and call set_id in the initialize method, it doesn’t work. Why? I’d rather do it there automatically than have to call guest.set_id in my controller.

Happy to answer any questions if this isn’t clear.

-Roneesh


(Alex Bush) #2

I believe you should do this kind of assignment/check in a setter method instead.