在rails項目中,我有3個控制器和模型,用戶,責任和配置文件。我有下面的代碼:before_create在rails中不起作用
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
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' - t的一些內置的主動記錄方法?或者爲什麼你沒有展示它? – zishe
發佈您的'before_create'代碼,以便找到解決方案。 – Pavan
看起來像它真的在[方法]中構建(http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#method-i-belongs_to) – zishe