rails找到相关的模型

时间:2014-07-09 19:55:04

标签: ruby-on-rails ruby-on-rails-4

我开始使用rails 4.xx

在rails上查找关系belongs_to或has_many的最佳方法是什么 我尝试使用类似于cakephp

的可包含行为的东西

我尝试了几个东西,但我找不到一个解决方案,所有不同版本的导轨。

我们可以用红宝石做到吗? imbri对象?如果不是.....你是如何做类似的事情的?

class Article < ActiveRecord::Base
  belongs_to :user
  belongs_to :category
end


class Category < ActiveRecord::Base
  has_many :articles
end

class User< ActiveRecord::Base
  has_many :articles
end

@example。 = Article.all

- !ruby/object:Article
  attributes:
    id: 1
    nb_acces: 1
    user_id: 1
              id: 1
              title: admin

    title: dsadasd
    slug: sadsa
    category_id: 3
                id: 3
                title: dsadasd

    summary: asdas
    content: dsadsa
    online: 1
    top: 1
    photo: fsdfsd
    photo_dir: dfsdf
    comment_count: 1
    created_at: 2014-07-09 10:28:50.000000000 Z
    updated_at: 2014-07-09 10:48:16.000000000 Z

- !ruby/object:Article
  attributes:
    id: 2
    nb_acces: 1
    user_id: 1
              id: 1
              title: admin

    title: dsadasd
    slug: sadsa
    category_id: 3
                id: 3
                title: dsadasd

    summary: asdas
    content: dsadsa
    online: 1
    top: 1
    photo: fsdfsd
    photo_dir: dfsdf
    comment_count: 1
    created_at: 2014-07-09 10:28:50.000000000 Z
    updated_at: 2014-07-09 10:48:16.000000000 Z

instead of

- !ruby/object:Article
  attributes:
    id: 1
    nb_acces: 1
    user_id: 1
    title: dsadasd
    slug: sadsa
    category_id: 3
    summary: asdas
    content: dsadsa
    online: 1
    top: 1
    photo: fsdfsd
    photo_dir: dfsdf
    comment_count: 1
    created_at: 2014-07-09 10:28:50.000000000 Z
    updated_at: 2014-07-09 10:48:16.000000000 Z

1 个答案:

答案 0 :(得分:2)

除非另行指定,否则所有关系都是延迟加载的。虽然数据可能不会显示在您的YAML导出中,但数据可用。

article = Article.first
author_name = article.user.name

上面将执行两个SQL查询来检索数据,一个用于文章,一个用于用户。它将检索用户记录并使用用户的名称值填充author_name。类别也是如此,它也可用,并将执行另一个SQL查询来检索数据。

articles = Article.all
author_names = articles.collect {|a| a.user.name}

以上是一个n + 1查询,它将对文章执行1次查询,然后对每篇文章执行1次查询以获取用户。如果您有20篇文章,您将执行20个作者查询和一篇文章查询。这是低效的,因此您应该包括用户。

articles = Article.includes(:user).all
author_names = articles.collect {|a| a.user.name}

以上只会执行2个查询,无论有多少文章。如果您想让用户和类别只包括它们:

articles = Article.includes(:user, :category).all
author_names = articles.collect {|a| a.user.name}
category_names = articles.collect {|a| a.category.name}

这将执行总共3个查询。

此外,如果您尝试get the YAML,则必须转换为xml并执行包含:

puts Hash.from_xml(articles.to_xml(include: [:user, :category])).to_yaml
相关问题