Will
Will

Reputation: 8282

local methods act differently when called with/without self. Why?

I have model called User with a has_many relationship to UserFilter. UserFilter has a belongs_to relationship to User.

Within the User model I have a method called update_user_filters(filter_params_array)

This method modifies user_filters like something like this

def update_user_filters(filter_params_array)
  new_filters = []
  old_filter = user_filters 

  filters_params_array.each do |filter_params|
    if filter_params[:id].blank? #if the filter does not yet exist
      new_filters << UserFilter.new(filter_params)
    end
  end
  user_filters = new_filters
end

This sets the user_filters to the expected value but upon saving it does not update the user_filters in the db.

however if I change the assignment to the following it does. Can someone explain why this is?

self.user_filters = new_filters

Note that when I first refer to user_filters in the model is does a select in the db so I am not sure how this local method is working differently with self and without self

Upvotes: 0

Views: 221

Answers (1)

Peter
Peter

Reputation: 132247

user_filters just creates a local variable. self.user_filters assigns it to the object. you probably want @user_filters = ....

Upvotes: 6

Related Questions