daveomcd daveomcd - 1 month ago 8
Ruby Question

Why am I getting two different sets of values from my Ruby object when using .to_hash?

I have an object in my Rails project, and when I do

record.to_hash
I get values, but I'm missing at least one -- notably
experience
. When I do record.attributes.to_hash I get more options including the attribute
experience
. Here's my output from using byebug below. Can anyone explain why this is the case? I was using
record.to_hash
in conjunction with
update_attributes
method to update an object but I need the additional attributes.

record.to_hash
#=> {:player_url=>"http://www.unlvrebels.com//sports/m-footbl/mtt/casey_acosta_1024286.html", :headshot_url=>nil, :jersey=>"87", :first_name=>"Casey", :last_name=>"Acosta", :position=>"WR", :height=>"5110", :weight=>"160", :eligibility=>nil, :hometown_city=>"Las Vegas", :hometown_state=>"NV", :high_school=>"Chaparral HS", :biography_text=>nil, :is_basketball_player=>false, :possible_dob=>false, :possible_transfer=>false, :possible_redshirt=>false, :possible_gpa=>false, :possible_track_participant=>false, :possible_basketball_participant=>false, :possible_baseball_participant=>false, :possible_hockey_participant=>false, :possible_lacrosse_participant=>false, :possible_power_lifting_participant=>false, :possible_rugby_participant=>false, :possible_soccer_participant=>false, :possible_volleyball_participant=>false, :possible_wrestling_participant=>false, :possible_medical_alert=>false, :possible_character_alert=>false, :school_id=>664, :player_id=>nil, :position_id=>2}
record.attributes.to_hash
#=> {"id"=>nil, "school_site_id"=>nil, "player_url"=>"http://www.unlvrebels.com//sports/m-footbl/mtt/casey_acosta_1024286.html", "headshot_url"=>nil, "jersey"=>"87", "first_name"=>"Casey", "last_name"=>"Acosta", "position"=>"WR", "height"=>"5110", "weight"=>"160", "eligibility"=>nil, "hometown_city"=>"Las Vegas", "hometown_state"=>"NV", "high_school"=>"Chaparral HS", "major"=>nil, "previous_school"=>nil, "experience"=>"FR", "biography_text"=>nil, "has_relative_in_sports"=>false, "is_basketball_player"=>false, "possible_dob"=>false, "possible_transfer"=>false, "possible_redshirt"=>false, "possible_gpa"=>false, "possible_track_participant"=>false, "possible_basketball_participant"=>false, "possible_baseball_participant"=>false, "possible_hockey_participant"=>false, "possible_lacrosse_participant"=>false, "possible_power_lifting_participant"=>false, "possible_rugby_participant"=>false, "possible_soccer_participant"=>false, "possible_volleyball_participant"=>false, "possible_wrestling_participant"=>false, "possible_medical_alert"=>false, "possible_character_alert"=>false, "school_id"=>664, "player_id"=>nil, "position_id"=>2, "created_at"=>nil, "updated_at"=>nil}

Answer

record is an instance of Record class, whereas record.attributes is an instance of Hash class.

The difference probably occur because to_hash method implemented differently for instances of these two classes.