gpt4 book ai didi

ruby-on-rails - before_create 在 Rails 中不起作用

转载 作者:行者123 更新时间:2023-12-04 06:36:54 27 4
gpt4 key购买 nike

在 Rails 项目中,我有 3 个 Controller 和模型,用户、职责和配置文件。我有以下代码:
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它不起作用,也不会创建新的配置文件。 profile有区别吗和 responsibility ?为什么 before_create适用于 responsibility ,但不适用于 profile ?

最佳答案

这几乎肯定是 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 来进行测试。 & presence您的 Profile 中的验证模型:
#app/models/profile.rb
class Profile < ActiveRecord::Base
belongs_to :user

# -> test without validations FOR NOW
end

关于ruby-on-rails - before_create 在 Rails 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23708576/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com