2011-10-11 47 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

嘿拉里我想出了,因为你的消息在另一个线程“模型属性被实现为方法。仔细检查属性名称的拼写和大写与常量数组中的名称。”如果你想添加到你的答案上面,我会给你这个复选标记。再次感谢。 –

相关问题