新手问题 many_to_many 的数据查询问题

metal · 2012年08月09日 · 最后由 metal 回复于 2012年08月09日 · 1691 次阅读

我有 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

好吧我又搞定了。我抱着试试看的态度吧 each 改成 collect,结果就可以了。

只是我有点不明白 each 和 collect 有什么具体差别。

需要 登录 后方可回复, 如果你还没有账号请 注册新账号