【问题标题】:Rails 3: getting undefined method when trying to use a variable in a blockRails 3:尝试在块中使用变量时获取未定义的方法
【发布时间】:2011-10-11 02:14:37
【问题描述】:

我收到undefined method 'social_system' for #User:0x000001052e2ad8。我以为我会使用块中的值,谁能解释我做错了什么?

# 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
%>

【问题讨论】:

  • 据我所知,这应该可行。我假设错误来自@user.send(social_system) 行。您使用的是哪个版本的 Ruby?您可以尝试 @user.send(social_system.to_sym),但这只是一个猜测,因为send 方法应该能够很好地接受字符串,除非Ruby 1.9.2 中存在我不知道的差异'不知道。

标签: ruby-on-rails ruby-on-rails-3 methods


【解决方案1】:

嗯,因为错误消息是

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
%>

【讨论】:

  • 我不得不删除注释行,但后来我得到“social_system = facebook_url Facebook social_system = google_plus_url Google +”,这是我们想要的正确吗?
  • 嘿拉里我想通了,因为您在另一个线程上的消息“模型属性作为方法实现。仔细检查属性名称的拼写和大小写与常量数组中的名称。”如果您想将其添加到上面的答案中,我会给您打勾。再次感谢。
猜你喜欢
  • 1970-01-01
  • 2013-05-21
  • 2012-06-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多