2009-09-21 58 views
0

我正試圖完成非典型庫學習語言應用程序。我已經能夠創建書籍,人員和BookCheckOut。我的關係工作得很好,但是我在處理那些從未被檢出的書的時候遇到了問題。當在Ruby on Rails中找不到任何記錄時該怎麼辦

我在我的書類CheckedOut(返回一個布爾值)和LastCheckedOutTo(返回一個人)上創建了兩個屬性。我非常喜歡CheckedOut,並且確信我正在使用正確的RoR機制來確定一本書目前是否已簽出並返回布爾值。我對LastCheckedOutTo沒有那麼自信,因爲我的實現看起來像一團糟。

我是否正確地處理這個問題?有沒有更好的辦法?

Book類的全部

class Book < ActiveRecord::Base 
    has_many :book_check_outs 
    has_many :people, :through => :book_check_outs 

    def checked_out 
    if (book_check_outs.find(:first, :conditions => "return_date is null")) 
     true 
    else 
     false 
    end 
    end 

    def last_checked_out_to 
    if (book_check_outs.count > 0) 
     book_check_outs.find(:first, 
     :order => "out_date desc").person 
    else 
     Person.new() 
    end 
    end 
end 

回答

4

也許:

class Book < ActiveRecord::Base 
    has_many :book_loans 
    has_many :borrowers, :class_name => 'Person', :through => :book_loans 

    def loaned? 
    book_loans.exists?(:return_date => nil) 
    end 

    # I would be reluctant to return a new Person object 
    # just because it was not checked out by anyone, instead you could return nil 
    # OR exception out. 
    def current_borrower 
    book_loans.first(:order => "out_date desc").person 
    end 
end 

# you can use a helper to keep your presentation clean 
module BookHelper 
    def borrower_name(book) 
    if borrower = book.borrower 
     borrower.name 
    else 
     "not checked out" 
    end 
    end 
end 
+0

我會使用嘗試(:人),這樣它不會被炸出來。 – 2009-09-21 13:09:02

+0

好的,我怎麼處理我的看法last_checked_out_to。我會盡量不要讓一堆邏輯流入模型的視圖。具體而言,如何解決書籍查看問題,但在書籍從未檢出的情況下不會出錯,從而使last_checked_out_to無。 – ahsteele 2009-09-22 01:25:23

+0

我想更好的重述是,而不是LastCheckedOutTo,如果它是CurrentlyCheckedOutTo。 – ahsteele 2009-09-22 01:28:45

0
  1. 關於def checked_out我 其重命名爲checked_out?,因爲 有不成文的(或可能 書面)紅寶石約定,任何 方法返回true或下跌 以問號結束。
  2. 第二種方法幾乎可以, ,但對於重度網站 而言,它不會很好。我建議反正規 這部分和 last_checked_out_to_id屬性 書籍表並更新它後 每個結帳過程。其他方式 將爲 book_check_outs.last.person爲 現有人和 book_check_outs.people.build爲新的。
1

實際上有很多方法可以做到這一點。這裏有一些想法:

您可以添加順序和另一個has_many因爲你真正關心的回覆日期:

has_many :book_check_outs, :order => "out_date asc" 
    has_many :current_book_check_outs, :conditions=>'return_date is null' 

然後你得到:

def checked_out? 
    current_book_check_outs.any? 
end 

def last_checked_out_to 
    if (book_check_outs.count > 0) 
    book_check_outs.last.person 
    else 
     Person.new() 
    end 
end 

但我有點困惑關於我如何使用last_checked_out_to。如果沒有最後一個人,我認爲我寧願它返回nil

你應該檢查出命名示波器,因爲那些幫助模塊化建立這些動態查詢。他們在這裏工作得很好。

雖然你在這段代碼中沒有使用person(people?),但是我會稍微修改一下這個術語,使它更好。 book.persons對於它告訴我們的內容並不太合適。圖書館員稱他們爲什麼? book.checker_outters什麼的?

相關問題