2013-06-05 31 views
0

我是Ruby on Rails的新手,並且正在使用應用程序中已有的一些代碼。瞭解rails 3.2中的控制器中的SQL代碼

的代碼如下(書): -

def index 
     @books = Book 
     @books = @books.select("books.*, 
           (select count(*) from book_issues where books.id = book_issues.book_id and book_issues.return_date is null) as issued_cnt, 
           (select count(*) from book_holds where books.id = book_holds.book_id) as hold_cnt") 
     @books = @books.joins("inner join book_issues on book_issues.book_id = books.id") 
     @books = @books.where('book_issues.return_date is null') 
     @books = @books.group('books.id') 
     @books.all 

     respond_to do |format| 
      format.html # index.html.erb 
      format.json { render json: @books } 
     end 
    end 

我發現這一點很難understand.Why是這個代碼中使用了,爲什麼不使用下面的代碼: -

def index 
    if params[:book_id] 
    @book = Book.find(:all, 
         :conditions => ["book_id = ? ", params[:book_id] ], 
         :order  => "action_date ASC")  
    end 
end 

有人可以幫助我這個。

+0

第二個塊是完全不同的,它應該用於'show'動作而不是'index' .. –

+0

那個控制器的動作沒有意義。你打算做什麼? – kiddorails

+0

@kiddorails我其實不知道,但代碼似乎適用於索引。它顯示數據庫中存在的所有書籍列表。 – Catmandu

回答

1

我想你會發現Rails guide的ActiveRecord部分非常有幫助。我建議給ActiveRecord querying文檔進行徹底的閱讀。密切關注示例的一般風格。 MVC(模型 - 視圖 - 控制器)模式的一個最強大的方面是,您可以在模型中構建非常簡單的接口來完成「繁重的工作」,而不是使用真正不屬於那裏的邏輯混淆控制器。

3

閱讀關於軌道中的關聯和作用域的手冊和教程。 這之後,你應該代碼改寫爲這樣的:

#model 

class Book < ActiveRecord::Base 
    # Association for BookIssue, the BookIssue model should have a 'belongs_to :book' 
    has_one :book_issue 
    # Association for BookHold, the BookHold model should have a 'belongs_to :book' 
    has_one :book_hold 
    # Scope to get not returned books, it joins all issues that don't have a return date. 
    # All book with a return date will be ignored. 
    scope :not_returned, joins(:book_issue).where(:book_issues => { return_date: nil }) 

end 

#controller 

def index 
    # Use the scope mentioned in the model, to get all not returned books. 
    @books = Book.not_returned.all 

    respond_to do |format| 
    format.html # index.html.erb 
    format.json { render json: @books } 
    end 
end 
+0

thx爲您的時間和幫助 – Catmandu

3

這裏正在解決的問題是「產生的當前未簽出書的數組,並把它傳遞給模板引擎上呈現的主要問題這一頁」。該SQL代碼正在處理第一部分。不幸的是,你必須加入反對book_issues,看看是否有任何可用的副本,但現在不管你想要定義像:available?這樣的書上的方法,當至少有一個副本沒有檢出,然後返回true時在你的控制器中使用它。

作爲進一步的調整,我想對書中記載,讓我知道,如果他們是可供檢出不加入反對book_issues表的數據庫列(BooksController中#指數聽起來像它會是調用了很多,你不希望它顛覆數據庫)。這可能意味着更新您的圖書結帳邏輯來調整主書記錄。

的代碼將是非常美好的,如果是這樣的:

#books controller 
def index 
    @books = Book.available 

    respond_to ... # continue as before 
end 

# book model 
scope :available, where(copies_available: true) 

# book_issue model 
belongs_to :book 
after_save :update_parent_availability 

def available? 
    return_date.nil? 
end 

def update_parent_availability 
    book.copies_available = book.issues.select(&:available?).any? 
    book.save if book.changed? 
end 

:update_parent_availability行動可能會受到競爭條件。你可能應該將它分解成一個幫助器書籍可用性管理類,並在事務中運行它。

+1

thx爲您的時間和幫助 – Catmandu