WallE WallE - 1 year ago 60
Ruby Question

How do I set the default value of an object equal to the current user's value for that same attribute of the current user? (Rails 4)

What I want to do:
Have a User who is currently logged on ("current_user") create a new instance of the Adult class ("adult") and - if current_user does not specify the number of kids (num_kids) that adult has AND current_user specifies that adult.relationship of adult to user is "husband", "wife" or "partner", then I want to set the value of adult.num_kids equal to the existing value of user.num_kids

I have a User class and an Adult class. A User has_many Adults and an Adult belongs_to a User.

I have a current_user helper method defined in my application_controller:

class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
helper_method :current_user

def current_user
current_user ||= User.find(session[:user_id]) if session[:user_id]

In my Adults Controller / create function I have the line:
@adult.user_id = current_user.id

This works fine, and I am able to create Adults with the correct reference to the User that the Adult belongs_to.

In my Adult model, I have:

class Adult < ActiveRecord::Base
has_many :kids
belongs_to :user

after_initialize :defaults
after_create :defaults_shared_info

def defaults
self.vacation_days ||= '10'

def defaults_shared_info
if ['husband', 'wife', 'partner'].any? { self.relationship }
self.num_kids ||= User.find(self.user_id).num_kids

The setting of vacation_days = 10 by default works fine.

However, the setting of the Adult's num_kids to the User's num_kids does not, and I end up with adult.num_kids = nil

I have confirmed that user.num_kids = 2 , so that is not the problem.

When I change the code to

def defaults_shared_info
if ['husband', 'wife', 'partner'].any? { self.relationship }
self.num_kids ||= current_user.num_kids

I get the error message "undefined local variable or method `current_user'"

I had initially tried NOT distinguishing between after_initialize and after_create, and had had all the code under
after_initialize :defaults

This also gave the same error "undefined local variable or method `current_user'"

I am confused about why, if I can create an instance of Adult with reference to the current_user.id, the code above is not working.

Answer Source

By changing after_create to before_create, I got this working.

Thanks to the folks posting here: http://stackoverflow.com/a/21757230/4797451

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download