通過我的第一個Rails應用程序工作。它將用於搜索和查看某些類別內書籍的數據。有條件地顯示多對多關係中的資源 - Rails 4
兩種資源:Categories
和Books
。我創建了一個多對多的HMT(有很多直通式的)關係(跟在this RailsCast之後),因爲每個類別都有很多書,每本書都屬於多個類別。下面是相關的控制器代碼:
分類模型(category.rb)
class Category < ActiveRecord::Base
has_ancestry
has_many :categorizations
has_many :books, :through => :categorizations
end
Book模型(book.rb)
class Book < ActiveRecord::Base
has_many :categorizations
has_many :categories, :through => :categorizations
accepts_nested_attributes_for :categories
end
加入模型(categorization.rb)
class Categorization < ActiveRecord::Base
belongs_to :book
belongs_to :category
end
而這裏的數據庫模式:
schema.rb
create_table "books", force: true do |t|
t.string "title"
t.string "url"
t.integer "rank_overall"
t.integer "rank_category"
t.decimal "price"
t.integer "reviews"
t.decimal "rating"
t.date "published"
t.string "img_cover"
t.string "author"
t.datetime "created_at"
t.datetime "updated_at"
t.string "asin"
t.integer "length"
end
create_table "categories", force: true do |t|
t.string "name"
t.text "content"
t.string "ancestry"
t.datetime "created_at"
t.datetime "updated_at"
end
add_index "categories", ["ancestry"], name: "index_categories_on_ancestry", using: :btree
create_table "categorizations", force: true do |t|
t.integer "book_id"
t.integer "category_id"
t.integer "rank"
t.datetime "created_at"
t.datetime "updated_at"
end
add_index "categorizations", ["book_id"], name: "index_categorizations_on_book_id", using: :btree
add_index "categorizations", ["category_id"], name: "index_categorizations_on_category_id", using: :btree
我有一個顯示視圖,顯示每個類別。在這個視圖中,我想展示每個相應類別中的書籍。我有這些簡單的循環:
.col-1-3
%strong TITLE
%ul
- @books.each do |book|
%li= book.title
.col-1-3
%strong AUTHOR
%ul
- @books.each do |book|
%li= book.author
.col-1-3
%strong ULR
%ul
- @books.each do |book|
%li= book.url
在我的分類模型我有以下幾點:
def show
@books = Book.order("title").includes(:categorizations).select("books.*")
end
def book_params
params.require(:book).permit(:books => [{:title => [:book_id]}, {:id => [:category_id]}, :author, :url])
end
下面是我的看法,我從所有接收信息的問題,從環書籍(即:書名,作者和全部數據庫中的書籍),我只希望從那些特定類別的書中獲得書籍。
我相信我需要改變我的categories_controller.rb
的邏輯,這是正確的嗎?我意識到我正在選擇所有書籍.select("books.*")
,但我不知道如何編輯此條件以僅有條件地僅調用與show
視圖中顯示的類別相匹配的書籍。
感謝您的見解。
更新: 認識到這個信息也是相當有幫助的。當圖書(書時創建)指定類別我用這個代碼:
= check_box_tag "book[category_ids][]", category.id, @book.category_ids.include?(category.id), id: dom_id(category)
也許是可能以某種方式引用dom_id(category)
類型模型的內部?
原諒我的「新生」。我是一個前端的人,現在纔剛剛開始進入後端。
如果您將視圖添加到頂部(在第一個「.col-1-3」之上),您只能在視圖中使用一個循環。 – cortex
嗯......這些循環是每個'.col-1-3'列的*內部*,它們顯示正常。正如已經提到的那樣,問題是我得到*全部*書籍和他們的數據,當我只想要那些在他們各自類別中的書。這就是這裏的問題。 –
當然,這就是爲什麼將它添加到評論中而不是答案。最好使用一個循環而不是三個;)爲了性能。 – cortex