访问活动记录模型时堆栈太深错误

时间:2014-03-28 21:03:14

标签: ruby-on-rails activerecord

所以我有一个用户对象和我生成的角色对象。角色对象有一个" belongs_to"与用户对象的关系。

class Character < ActiveRecord::Base
    belongs_to :user
end

但每当我尝试为所有这些字符创建新字符或查询时,它都会抛出以下错误:

Started GET "/characters" for 127.0.0.1 at 2014-03-28 15:54:28 -0500
  ActiveRecord::SchemaMigration Load (0.6ms)  SELECT "schema_migrations".* FROM "schema_migrations"
Processing by CharactersController#index as HTML
  Character Load (0.7ms)  SELECT "characters".* FROM "characters"
  Rendered characters/index.html.erb within layouts/application (15.9ms)
Completed 500 Internal Server Error in 38ms

ActionView::Template::Error (stack level too deep):
  activerecord (4.0.2) lib/active_record/attribute_methods/read.rb:84

我的索引操作:

def index
  @characters = Character.all
end

我的创建角色方法:

  # GET /characters/new   
  def new
      @character = Character.new(:user_id => current_user.user_id)
  end

我所做的所有谷歌搜索都引发了一些递归问题,但我不知道如何以递归方式调用任何内容。

修改

我的index.html.erb用于角色模型:

<h1>Listing characters</h1>

<table>
  <thead>
    <tr>
      <th></th>
      <th></th>
      <th></th>
    </tr>
  </thead>

  <tbody>
    <% @characters.each do |character| %>
      <tr>
        <td><%= link_to 'Show', character %></td>
        <td><%= link_to 'Edit', edit_character_path(character) %></td>
        <td><%= link_to 'Destroy', character, method: :delete, data: { confirm: 'Are you sure?' } %></td>
      </tr>
    <% end %>
  </tbody>
</table>

<br>

<%= link_to 'New Character', new_character_path %>

我的用户模型(使用Devise创建):

class User < ActiveRecord::Base
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable
end

我也在rails控制台中尝试过它:

2.0.0p247 :002 > Character.all
  Character Load (1.0ms)  SELECT "characters".* FROM "characters"
SystemStackError: stack level too deep
    from /Users/mam8cc/.rvm/gems/ruby-2.0.0-p247/gems/activerecord-4.0.2/lib/active_record/attribute_methods/read.rb:59

1 个答案:

答案 0 :(得分:1)

这里是由栈跟踪识别的Rails代码:

# activerecord-4.0.2/lib/active_record/attribute_methods/read.rb:59

def define_method_attribute(name)
  safe_name = name.unpack('h*').first
  generated_attribute_methods::AttrNames.set_name_cache safe_name, name

  generated_attribute_methods.module_eval <<-STR, __FILE__, __LINE__ + 1
    def __temp__#{safe_name}
      read_attribute(AttrNames::ATTR_#{safe_name}) { |n| missing_attribute(n, caller) }
    end
    alias_method #{name.inspect}, :__temp__#{safe_name}
    undef_method :__temp__#{safe_name}
  STR
end

堆栈溢出发生在以read_attribute开头的行上。 Character模型中的属性名称有什么奇怪之处吗?我建议仔细查看,并列出表格中的列名。