2
我試圖找到一個特定類別的所有主題,但我不知道這是否是最有效的方式做到這一點:Ruby on Rails:查找某個類別中的所有主題?
Topic.all.select { |topic| topic.categories.include?(category) }
上述工作對我來說,但它似乎需要很長時間才能找到記錄。有什麼更有效率嗎?
我試圖找到一個特定類別的所有主題,但我不知道這是否是最有效的方式做到這一點:Ruby on Rails:查找某個類別中的所有主題?
Topic.all.select { |topic| topic.categories.include?(category) }
上述工作對我來說,但它似乎需要很長時間才能找到記錄。有什麼更有效率嗎?
這聽起來像是現在你在主題和類別之間有一個has_many關係,當你需要一個多對多的關係時。調整你的模式是這樣的:
# app/models/category.rb
class Category < ActiveRecord::Base
has_and_belongs_to_many :topics
end
# app/models/topic.rb
class Topic < ActiveRecord::Base
has_and_belongs_to_many :categories
end
然後創建一個連接表沒有主鍵。創建新的遷移,像這樣:
script/generate migration AddCategoriesTopicsJoinTable
並添加以下內容:
class AddCategoriesTopicsJoinTable < ActiveRecord::Migration
def self.up
create_table :categories_topics, :id => false do |t|
t.integer :category_id
t.integer :topic_id
end
end
def self.down
drop_table :categories_topics
end
end
通知連接表是通過結合兩個表名,按字母順序命名。這就是Rails如何知道如何自動找到它。
現在您可以撥打電話@category.topics
並獲得一系列主題,並且您可以撥打@topic.categories
並獲取類別。它可以在兩個方向上工作。
UPDATE:關於Rails的許多一對多的關係問題已經拿出往往不夠,我編寫了一個名爲basic many-to-many associations解釋如何使用habtm
VS has_many :through
的文章,以及它們之間的差異。
這是偉大的海梅。非常感謝! – andy 2010-01-29 18:34:54
不客氣,我很高興它幫助:) – 2010-01-29 20:02:55