2012-01-31 35 views
1

我正在建立一個婚禮網站,允許客人使用邀請碼和RSVP在線登錄。我的型號如下:Rails 3 - 創建具有嵌套屬性的資源的正確方法是什麼?

邀請

class Invitation < ActiveRecord::Base 

    attr_accessible # None are accessible 

    # Validation 
    code_regex = /\A[A-Z0-9]{8}\z/ 

    validates :code, :presence => true, 
        :length => { :is => 8 }, 
        :uniqueness => true, 
        :format => { :with => code_regex } 

    validates :guest_count, :presence => true, 
          :inclusion => { :in => 1..2 } 

    has_one :rsvp, :dependent => :destroy 
end 

RSVP

class Rsvp < ActiveRecord::Base 

    attr_accessible :guests_attributes 

    belongs_to :invitation 
    has_many :guests, :dependent => :destroy 
    accepts_nested_attributes_for :guests 

    validates :invitation_id, :presence => true 
end 

遊客

class Guest < ActiveRecord::Base 

    attr_accessible :name, :email, :phone, :message, :attending_wedding, :attending_bbq, :meal_id 

    belongs_to :rsvp 
    belongs_to :meal 

    email_regex = /\A[\w+\-.][email protected][a-z\d\-.]+\.[a-z]+\z/i 

    validates :name, :presence => true 
    validates :email, :allow_blank => true, :format => { :with => email_regex } 
    validates :attending_wedding, :inclusion => {:in => [true, false]} 
    validates :attending_bbq, :inclusion => {:in => [true, false]} 
    validates :rsvp_id, :presence => true 
    validates :meal_id, :presence => true 
end 

我的邏輯是我將爲數據庫播種邀請函,並且當訪客登錄到網站時,他們將會看到一個RSVP表單,每個訪客都使用一段(在視圖中使用form_for)。

我rsvps_controller新創造的行動是:

def new 
    @title = "Edit RSVP" 
    @rsvp = current_invitation.build_rsvp 
    current_invitation.guest_count.times { @rsvp.guests.build } 
    @meals = Meal.all 
    end 

    def create 
    @rsvp = current_invitation.build_rsvp(params[:rsvp]) 
    if @rsvp.save 
     flash[:success] = "RSVP Updated." 
     redirect_to :rsvp 
    else 
     @title = "Edit RSVP" 
     @meals = Meal.all 
     render 'new' 
    end 
    end 

既然這樣,這個代碼將不會保存RSVP,因爲它抱怨說,「客人RSVP不能爲空」。我知道這是(可能),因爲rsvp記錄尚未保存到數據庫,因此還沒有ID。我可以通過刪除rsvp_id上的驗證來解決這個問題,但感覺不對 - 畢竟,所有訪客記錄應該與RSVP有關聯,所以我認爲驗證應該保留。另一方面,沒有驗證,如果我通過控制檯查看記錄關聯是正確的。

處理這種情況的標準(慣用導軌)方式是什麼?

感謝, 諾埃爾

回答

0

你幾乎擊中了要害「因爲RSVP記錄尚未保存到數據庫」。該協會在那裏,rsvp_id不是。

雖然您可以創建自定義驗證程序。類似...

class Guest < ActiveRecord::Base 
    ... 
    validate :associated_to_rsvp 
    ... 
private 
    def associated_to_rsvp 
    self.errors.add(:rsvp, "does not exist.") unless self.rsvp 
    end 
end 
+0

嗨Azolo,謝謝你的回答。不幸的是,這並沒有解決問題。當使用'validates:rsvp_id,:presence => true'時,我得到相同的錯誤 – noelob 2012-02-22 19:24:54