堆栈级别太深:rails 2.3.8

时间:2014-05-14 21:11:13

标签: ruby-on-rails ruby activerecord model-associations

尝试将可选参数传递给rails模型方法时出错。 我的模型如下所示

Class Antigen 
has_and_belongs_to_many :projects

我想做

antigen = Antigen.first
antigen.projects(injection) 

甚至

antigen.projects

传递争论的模型方法

def projects(injection=nil)
    if injection == nil 
       return projects
    else 
       ..do something with injection and then pass projects
    end
end

为什么这不起作用

1 个答案:

答案 0 :(得分:2)

使用super:

而不是调用项目(你刚刚覆盖它们)
def projects(injection=nil)
  if injection == nil 
    return super()
  else 
   ..do something with injection and then pass projects
  end
end

我会稍微重构它以摆脱一个抽象层次:

def projects(injection=nil)
  return super() unless injection
  #..do something with injection and then pass projects
end

更新:

由于您使用的是rails 2.3.8 super,因此无法用于访问关联方法。而是尝试:

class Model < AR::Base
  has_and_belongs_to_many :proxy_projects, class_name: 'Projects'
  private :proxy_projects

  def projects(injection=nil)
    return proxy_projects unless injection
    #..do something with injection and then pass projects
  end
end