我是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
有人可以幫助我這個。
第二個塊是完全不同的,它應該用於'show'動作而不是'index' .. –
那個控制器的動作沒有意義。你打算做什麼? – kiddorails
@kiddorails我其實不知道,但代碼似乎適用於索引。它顯示數據庫中存在的所有書籍列表。 – Catmandu