2011-10-11 45 views
0

我得到undefined method 'social_system' for #User:0x000001052e2ad8。我以爲我會使用塊中的值,任何人都可以解釋我做錯了什麼?Rails 3:嘗試在塊中使用變量時獲取未定義的方法

# User model: 
facebook_url string 
google_plus_url string 

# Constants defined in User model: 
SOCIAL_SYSTEMS  = [ 'facebook_url', 'google_plus_url' ] 
SOCIAL_SYSTEM_NAMES = { 'facebook_url' => 'Facebook', 
         'google_plus_url' => 'Google +' } 

# View (going to be a helper eventually) 
<% User::SOCIAL_SYSTEMS.each do |social_system| 
     url = @user.send(social_system) 
     if url %> 
     <p><a href="<%= url %>"> 
      <%= User::SOCIAL_SYSTEM_NAMES[social_system] -%> 
     </a></p> 
<% end 
    end 
%> 
+0

據我所知,這應該工作。我假設錯誤來自'@ user.send(social_system)'行。你使用的是什麼版本的Ruby?你可以*嘗試* @user.send(social_system.to_sym)',但這只是一個猜測,因爲'send'方法應該能夠取得字符串,除非Ruby 1.9.2有所不同,我不知道。 – bricker

回答

0

嗯,由於錯誤味精是

undefined method 'social_system' for #User:0x000001052e2ad8.

即意味着「social_system」正在視爲字符串常量,而不是作爲變量。

嘗試回顯它以查看正在發送的內容。該變量social_system應該只有 'facebook_url', 'google_plus_url'

回聲測試值:

# View (going to be a helper eventually) 
<% User::SOCIAL_SYSTEMS.each do |social_system| 
%> 
<p>social_system = <%= social_system %> 
<% #  url = @user.send(social_system) 
    # if url %> 
    #  <p><a href="<%= url %>"> 
      <%= User::SOCIAL_SYSTEM_NAMES[social_system] -%> 
     </a></p> 
<% # end 
    end 
%> 
+0

我不得不刪除註釋行,但後來我得到了「social_system = facebook_url Facebook social_system = google_plus_url Google +」這是我們想要的正確嗎? –

+0

嘿拉里我想出了,因爲你的消息在另一個線程「模型屬性被實現爲方法。仔細檢查屬性名稱的拼寫和大寫與常量數組中的名稱。」如果你想添加到你的答案上面,我會給你這個複選標記。再次感謝。 –

相關問題