1

我的问题:用户 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

总是同样的错误。为什么?

4

1 回答 1

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
      |_ ...
于 2013-04-18T09:53:15.080 回答