before_create在rails中不起作用

时间:2014-05-17 07:03:01

标签: ruby-on-rails

在rails项目中,我有3个控制器和模型,用户,责任和配置文件。我有以下代码:

user.rb

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

  has_one :responsibility
  has_one :profile

  before_create :build_responsibility
  before_create :build_profile

end

responsibility.rb

class Responsibility < ActiveRecord::Base

  belongs_to :user

end

profile.rb

class Profile < ActiveRecord::Base

  belongs_to :user

  validates :user_id, uniqueness: true

  validates_numericality_of :nic_code, :allow_blank => true
  validates_numericality_of :phone_number

  validates_length_of :phone_number, :minimum => 11, :maximum => 11
  validates_length_of :nic_code, :minimum => 10, :maximum => 10, :allow_blank => true

  has_attached_file :photo, :styles => { :medium => "300x300>", :thumb => "35x35>" }, :default_url => "profile-missing.jpg"
  validates_attachment_content_type :photo, :content_type => [ 'image/gif', 'image/png', 'image/x-png', 'image/jpeg', 'image/pjpeg', 'image/jpg' ]

end

现在,当我创建新用户时,before_create适用于responsibility并创建它,但对于profile,它不起作用,并且不会创建新的配置文件。 profileresponsibility之间有区别吗?为什么before_create适用于responsibility,但不适用于profile

1 个答案:

答案 0 :(得分:3)

这几乎肯定是validation问题:

#app/models/profile.rb
validates_length_of :phone_number, :minimum => 11, :maximum => 11
validates_length_of :nic_code, :minimum => 10, :maximum => 10, :allow_blank => true

当您build一个ActiveRecord对象时,模型将不会填充数据。这意味着您的验证将无法验证数据,我相信这会引发错误

您需要删除length&amp; presence模型中的Profile次验证:

#app/models/profile.rb
class Profile < ActiveRecord::Base
  belongs_to :user

  # -> test without validations FOR NOW
end