2013-07-05 2 views
0

레일 4에서 나는 usertemplate에 대한 관계를 가진 메시지 모델을 가지고 있습니다. 또한 자체 속성 인 text이 있습니다. 여기 레일 4 모델 속성을 설정할 수 없습니다

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 

내 문제 : 나는 message = Message.create!(user: user, template: template, "hello world") message.text"hello world" 동일합니다 실행하면 (I 이미 usertemplate 있다고 가정) ,하지만 난 그가 데이터베이스에서이 레코드를 검색 할 때, 그것은 text 속성이 nil입니다입니다, 다른 모든 속성은 정상입니다.

무엇을 제공합니까? text이 데이터베이스에 저장되지 않는 이유는 무엇입니까?

+0

왜 attr_accessor : text를 사용하고 있습니까? 그런 식으로 ActiveRecord 텍스트 속성을 "덮어 씁니다"그리고 모든 동작이 그 것이기 때문에 아마도 db에 기록되지 않습니다. 텍스트는 예약어 (db type'text') 일 수 있으므로주의하십시오. –

답변

0
  1. ActiveRecord::Base.initialize 메서드를 재정의해야하는 이유는 무엇입니까? 이것은 일반적으로 나쁜 습관입니다. @user@template의 설정자는 전혀 필요하지 않습니다. Rails는 기본 initialize 메소드를 통해 모델 속성을 설정합니다.
  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 기능을 덮어 씁니다.

관련 문제