2013-07-05 106 views
0

在Rails 4中,我有一個消息模型,其關係爲usertemplate。它也有它自己的屬性,textRails 4 model屬性不可設置

class Message < ActiveRecord::Base 
attr_accessor :text 

belongs_to :user 
belongs_to :template 

validates :user, presence: true 
validates :template, presence: true 
validates :text, presence: true, if: lambda { |message| message.template.present? } 

    def initialize(args = {}) 
     super 
     @user = args[:user] 
     @template = args[:template] 
     @text = args[:text] || (args[:template].text if args[:template].present?) 
    end 

end 

這裏是我的問題: (假設我有一個usertemplate已經) 當我運行message = Message.create!(user: user, template: template, "hello world") message.text將等於"hello world",但是當我從中檢索自己的數據庫這個紀錄,這是text屬性爲nil,並且所有其他屬性都可以。

什麼給?爲什麼text不被保存到數據庫?

+0

爲什麼使用attr_accessor:text?這樣你就可以「覆蓋」ActiveRecord文本屬性及其所有行爲,這可能就是爲什麼它沒有寫入數據庫。另外要小心,文本可能是一個保留字(db type'text') –

回答

0
  1. 沒有理由給出你提供的代碼,爲什麼你應該重寫ActiveRecord::Base.initialize方法。這通常是不好的做法。根本不需要@user@template上的二傳手; Rails將通過基礎初始化方法爲您設置模型屬性。
  2. 您爲@text制定者應該在after_initialize

    after_initialize do 
        self.text = self.template if self.text.blank? && self.template.present? 
    end 
    
  3. 如果:text提供的默認功能是一個真正的模型屬性(列在數據庫匹配),你不應該在您的Message型號上撥打attr_accessor :text。它會對你不好,並且會覆蓋texttext=方法的ActiveRecord::Base功能。

相關問題