나는 가상 속성에 대한 사용자 정의 세터를 제공하고 레코드를 만든 후 값을 설정하는 after_create 훅을 제공하는 것이 일을 더 허용 방법을 생각한다.
다음 코드는 원하는대로 수행해야합니다. 콘솔이 실행
는
class Virt < ActiveRecord::Base
def after_create()
self.virtual_attr = nil # Set it to anything just to invoke the setter
save # Saving will not invoke this callback again as the record exists
# Do NOT try this in after_save or you will get a Stack Overflow
end
def virtual_attr=(value)
write_attribute(:virtual_attr, "ID: #{self.id} #{value}")
end
end
나는 그가 ID를 기반으로하는 virtual_attr라는 DB에 열이 있다고 가정 않은 다음
v=Virt.new
=> #<Virt id: nil, virtual_attr: nil, created_at: nil, updated_at: nil>
>> v.save
=> true
>> v
=> #<Virt id: 8, virtual_attr: "ID: 8 ", created_at: "2009-12-23 09:25:17",
updated_at: "2009-12-23 09:25:17">
>> Virt.last
=> #<Virt id: 8, virtual_attr: "ID: 8 ", created_at: "2009-12-23 09:25:17",
updated_at: "2009-12-23 09:25:17">
을 보여줍니다. –
일 수 있지만 일반적으로 속성은 해당 DB 열이 없기 때문에 가상입니다. 일반적으로 기존 열에서 파생됩니다. 레일스의 경우 가상 속성에 대한 다른 정의에 대해 들어 본 적이 없습니다. – EmFi
좋은 지적. 가상 속성 대신 파생 된 속성을 사용하는 질문에 대해 다시 말합니다. –