【发布时间】: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_create 为 responsibility 工作并创建它,但对于 profile 它不起作用并且不会创建新的配置文件。 profile 和 responsibility 有区别吗?为什么before_create 适用于responsibility,但不适用于profile?
【问题讨论】:
-
build_responsibility- 是一些内置的 activerecord 方法吗?或者你为什么不展示它? -
发布您的
before_create代码,以便轻松找到解决方案。 -
看起来确实是在method中构建的
-
before_create允许您使用build_[object]即时构建对象 - 它只是创建关联模型的空白版本,并填充您的foreign_key
标签: ruby-on-rails