rails4渴望加载超过2个型号

时间:2016-06-02 21:07:09

标签: ruby-on-rails activerecord eager-loading

我不确定我是否正确使用导轨急切加载。

我想在视图中致电post.user.profile.first_name,感谢授权,post.user.name只是belongs_to :user 。我想用一个查询来做,所以配置文件应该与用户一起加载第一个查询。我不确定我是否做得很好。

这是要走的路吗?

profile.rb

has_one :profile
delegate :first_name, .... , to: :profile, allow_nil: true
has_many :posts

user.rb

belongs_to :user
has_one :user_profile, through: :user, source: :profile

post.rb

Post.includes(:user, :user_profile).paginate.......

posts_controller

UserWarning: Support for Python 3.0-3.2 has been dropped. Future versions will fail here.
Traceback (most recent call last):
  File "get-pip.py", line 19178, in <module>
    main()
  File "get-pip.py", line 195, in main
    bootstrap(tmpdir=tmpdir)
  File "get-pip.py", line 82, in bootstrap
    import pip
  File "/tmp/tmpec9tur/pip.zip/pip/__init__.py", line 16, in <module>
  File "/tmp/tmpec9tur/pip.zip/pip/vcs/mercurial.py", line 9, in <module>
  File "/tmp/tmpec9tur/pip.zip/pip/download.py", line 36, in <module>
  File "/tmp/tmpec9tur/pip.zip/pip/utils/ui.py", line 15, in <module>
  File "/tmp/tmpec9tur/pip.zip/pip/_vendor/progress/bar.py", line 48
    empty_fill = u'∙'
                      ^
SyntaxError: invalid syntax

1 个答案:

答案 0 :(得分:2)

尝试:

Post.joins(user: :profile).includes(user: :profile).paginate

joins是为了确保内部联接,以实现高效准确的查询。正如您所知,includes适用于急切负载。