2012-01-13 4 views

답변

7

패스는 같이 객체에 해시 속성 :

당신이 레일에 루비를 처음 사용하는 경우
post = Post.new(:vote_total => 123, :author => "Jason Bourne", ...) 

, 당신은 아마 이것과 더 많은 커버 Getting Started Guide을 읽을 수 있도록 할 것 유용한 레일즈 관용구를 자세히 설명합니다.

+0

그래, 내가 예를 들어 이것을 사용했는데, 내가 투표를 원할 때 더 복잡한 Instanciation을 원한다면 어떻게해야합니까? post()는 자동으로 post의 vote_total을 증가시켜야합니까? – user1144442

+0

그런 경우 Vote.add_post (post)와 같이 Vote 모델에서 메소드를 만드는 것이 더 합리적 일 것이며, 내부적으로'add_post' 메소드는 vote_total을 증가시킬 수 있습니다. – MrDanA

2

내가 사용하는 것 콜백 : 당신이 상점 기본 값으로 데이터베이스를 허용 할 수 Available Callbacks

class Post 
    before_save :set_defaults 

    def set_defaults 
     self.vote_total ||= 0 
     #do other stuff 
    end 
end 
0

당신

class AddColumnWithDefaultValue < ActiveRecord::Migration 
    def change 
    add_column :posts, :vote_total, :integer, :default => 0 
    end 
end 

또는 기존 테이블

:

class ChangeColumnWithDefaultValue < ActiveRecord::Migration 
    def up 
    change_column_default(:posts, :vote_total, 0) 
    end 
    def down 
    change_column_default(:posts, :vote_total, nil) 
    end 
end 

가있다 그래도 많은 토론이 storing default values in the database에 관한 것입니다.

관련 문제