before_create 在 Rails 中不起作用

mgh*_*mgh 4 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
Run Code Online (Sandbox Code Playgroud)

responsibility.rb

class Responsibility < ActiveRecord::Base

  belongs_to :user

end
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

现在,当我创建一个新用户时,before_createresponsibility它工作并创建它,但因为profile它不起作用并且不会创建新的配置文件。有没有之间的差异profileresponsibility?为什么before_create对 有效responsibility,但对 无效profile

Ric*_*eck 5

这几乎肯定是一个验证问题:

#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
Run Code Online (Sandbox Code Playgroud)

当您build使用 ActiveRecord 对象时,模型将不会填充数据。这意味着您的验证将没有要验证的数据,我相信这会引发错误

您需要通过删除模型中的length&presence验证来进行测试Profile

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

  # -> test without validations FOR NOW
end
Run Code Online (Sandbox Code Playgroud)