before_create doesn't work in rails

爱⌒轻易说出口 提交于 2021-02-19 02:42:27

问题


In a rails project, I have 3 controllers and models, user, responsibility and profile. I have below code:

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

Now, when I created a new user, before_create works for responsibility and creates it, but for profile it's not working and doesn't create a new profile. Is there a difference between profile and responsibility? Why before_create works for responsibility, but doesn't work for profile?


回答1:


This will almost certainly be a validation issue:

#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

When you build an ActiveRecord object, the models will not be populated with data. This means your validations are going to have no data to validate, which I believe will throw the error

You need to test by removing the length & presence validations in your Profile model:

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

  # -> test without validations FOR NOW
end


来源:https://stackoverflow.com/questions/23708576/before-create-doesnt-work-in-rails

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!