截至 2012-08-11 08:55:52 +0800,共收到 3 條回應
Kenn
1樓, 於2012-08-09 21:07:30 +0800回應
想了一下,自己有了一些眉目,用many_to_many就可以实现。
现在碰到一个数据查询的问题。
我有3个表
- posts
- categories
- categorizations
categorizations就是中间表,里面自然有post_id和category_id
我在rails console里输入
Post.create(:title => "first post")
Category.create(:name => "hello")
Post.first.categories << Category.first
我现在要怎么通过Post.first找到Category.name或者Category.id
Post.first.categories
这样会得到所有的数据,我只想取category的id和name
lulalala
2樓, 於2012-08-10 09:47:19 +0800回應
第一種方式,資料庫層還是會全部資料抓出來,所以沒有比較有效率:
Post.first.categories.map{|c| [c.id, c.name]}
第二種方式,只會抓這兩個欄位,但是抓出來的 model 會是唯讀的:
Post.first.categories.select("categories.id, categories.name")
我覺得不太需要作這種迷你的最佳化就是了。