【问题标题】:before_create doesn't work in railsbefore_create 在 Rails 中不起作用
【发布时间】:2014-07-05 16:35:45
【问题描述】:

在一个 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_createresponsibility 工作并创建它,但对于 profile 它不起作用并且不会创建新的配置文件。 profileresponsibility 有区别吗?为什么before_create 适用于responsibility,但不适用于profile

【问题讨论】:

  • build_responsibility - 是一些内置的 activerecord 方法吗?或者你为什么不展示它?
  • 发布您的before_create 代码,以便轻松找到解决方案。
  • 看起来确实是在method中构建的
  • before_create 允许您使用 build_[object] 即时构建对象 - 它只是创建关联模型的空白版本,并填充您的 foreign_key

标签: ruby-on-rails


【解决方案1】:

这几乎肯定是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 对象时,模型将不会填充数据。这意味着您的验证将没有要验证的数据,我相信这会引发错误

您需要通过删除 Profile 模型中的 lengthpresence 验证来进行测试:

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

  # -> test without validations FOR NOW
end

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2013-02-28
  • 2012-11-23
  • 1970-01-01
  • 2017-03-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-30
相关资源
最近更新 更多