代码之家  ›  专栏  ›  技术社区  ›  John Smith

模块导轨4中未定义的方法

  •  2
  • John Smith  · 技术社区  · 12 年前

    我编写了这个模块并将其保存在lib/Connect.rb中

    module Connect
      def self.fullname
        'Was'
      end
    end
    

    接下来,我在控制器中添加了:

    require "#{Rails.root}/lib/Connect.rb"
    

    那么在我看来:

    <% @employees.each do |employee| %> 
      <%= employee.fullname %>
      <h4><%= link_to "#{employee.vorname} #{employee.nachname}", nutzerverwaltung_path(employee.id) %></h4> 
      <% end %>
    

    不知怎么的,现在我明白了:

     undefined method `fullname' for #<Employee:0x37c1e68>
    

    我做错了什么?

    1 回复  |  直到 12 年前
        1
  •  1
  •   Billy Chan    12 年前

    不添加 self 这是针对类方法的。

      def fullname
        'Was'
      end
    

    在初始化程序中需要此文件,而不是在控制器中。

    您还需要在模型中包含此模块,因为这将扩展模型

    class Employee < ActiveRecord::Base
      include Connect