2014-05-17 70 views
3

在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它不起作用,不會創建新的配置文件。 profileresponsibility之間有區別嗎?爲什麼before_create適用於responsibility,但不適用於profile

+1

'build_responsibility' - t的一些內置的主動記錄方法?或者爲什麼你沒有展示它? – zishe

+1

發佈您的'before_create'代碼,以便找到解決方案。 – Pavan

+0

看起來像它真的在[方法]中構建(http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#method-i-belongs_to) – zishe

回答

3

這幾乎可以肯定將是一個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模型取出length & presence驗證測試:

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

    # -> test without validations FOR NOW 
end 
+0

我在所有驗證字段中設置了':allow_blank => true',這是工作,謝謝。 – mgh

+0

不錯!很高興幫助 –