堆栈级别太深:创建子记录

时间:2013-04-18 09:50:45

标签: ruby-on-rails

我的问题:用户has_one个人资料。创建新用户时,APP还会自动创建属于User的Profile。我试图通过控制器,通过回调,总是相同的错误(堆栈级别太深)。我的模特:

class User < ActiveRecord::Base
  has_secure_password
  attr_accessible :email, :password, :password_confirmation
  validates_uniqueness_of :email, :case_sensitive => false
  validates :email, :email_format => true
  validates :password, :length=> {:in=> 5...32}
  validates :email, :password, :password_confirmation, :presence =>true
  has_many :authentications
  has_many :tests
  has_many :answers
  has_many :results
  has_one :profile
  #after_create :build_profile
  #tried this way

  def build_profile
    self.build_profile
  end

end

class Profile < ActiveRecord::Base
      attr_accessible :user_id
      belongs_to :user
    end

  def create
        @user = User.new(params[:user])
        @user.email=@user.email.downcase
        if @user.save
          session[:user_id] = @user.id
          @profile=@user.build_profile
          redirect_to root_url, notice: "Thank you for signing up!"
        else
         render "new"
        end
      end

Alsways同样的错误。为什么呢?

1 个答案:

答案 0 :(得分:1)

def build_profile
  self.build_profile
end

这无休止地循环(我看不出重点,你想做什么?)

你应该简单地删除build_profile方法(不用担心,这是由于关联而定义的。)


user = User.new

user.build_profile
  |_ calls self.build_profile, but self is user
    |_ calls user.build_profile
      |_ ...