2016-11-02 27 views
0

我在我的Rails項目中有一個對象,當我做record.to_hash時,我得到了值,但我至少缺少一個值 - 特別是experience。當我做record.attributes.to_hash時,我會得到更多選項,包括屬性experience。這是我在下面使用byebug的輸出。任何人都可以解釋爲什麼這是事實嗎?我正在使用record.to_hashupdate_attributes方法來更新對象,但我需要額外的屬性。爲什麼在使用.to_hash時從我的Ruby對象中獲取兩組不同的值?

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} 

回答

3

recordRecord類的一個實例,而record.attributesHash類的一個實例。

由於to_hash方法對於這兩個類的實例的實現方式不同,可能會出現差異。

+0

所以,如果我使用的屬性,除了它的作品,它包括像'id'這樣的屬性。如果沒有通過附加代碼去除這些屬性,有沒有更多的Rails方法來做我想做的事情?不知道是否有我應該使用的方法。 – daveomcd

+0

@daveomcd'record.attributes'已經是'Hash'了,所以它*就是你想要的:)無需調用'to_hash'就可以了。 'record.attributes == record.attributes.to_hash' =>'true' –

+0

好吧,謝謝,我想這就是我用'update_attributes' - 'record.attributes.except('id','created_at' ,'updated_at')' – daveomcd

相關問題