简体   繁体   English

只需一次数据库调用即可将多个表中的数据存储在一个变量中(Rails)

[英]Store data from several tables in one variable with a single database call (Rails)

Assume these models: 假设这些模型:

class User < ActiveRecord::Base
  has_many :posts
end

class Post < ActiveRecord::Base
  belongs_to :user
  has_many :sections
end

class Section < ActiveRecord::Base
 belongs_to :post
 has_one :user, :through => :post
end

Assume this controller: 假设此控制器:

class SectionsController < ApplicationController
  def latest_sections
    @sections = Section.select(:name, :position, :updated_at)
                       .where(:public => true)
                       .order("updated_at DESC")
                       .limit(5)
  end
end

And finally this view: 最后是这个视图:

<ul>
  <% @sections.each do |section| %>
    <li>
      <h1>Section updated on: <%= section.updated_at %></h1>
      <%= section.position %> - <%= section.name %>
      <% post = section.post; user = section.user %>
      From Post: <%= link_to post.name, post %>
      By User: <%= link_to user.username, user %>
    </li>
  <% end %>
</ul>

My problem: 我的问题:

This causes several database calls for the post and user variables I am declaring in the view for each cycle of the each loop. 这将导致我在视图中针对每个循环的each循环在声明的postuser变量中进行多个数据库调用。

Is there a way for me to include all and only the information I need for the code above to work with a single database call and store it in the @sections variable (I'm assuming this will work with a joins). 有我包括所有和唯一的信息,我需要对上面的代码与一个单一的数据库调用工作,并将其存储在一个方式@sections变量(我假设这将与加入工作)。

In order words, I want to store this information in the @sections variable in a single database call: 换句话说,我想将此信息存储在单个数据库调用的@sections变量中:

  • section's name 部分name
  • section's updated_at 部分的updated_at
  • section's position 部门的position
  • section's user's username 部分用户的username
  • section's user's url_for 部分用户的url_for
  • section's post's name 该部分的帖子name
  • section's post's url_for 部分帖子的url_for

And how would I access this information? 我将如何访问这些信息?

(Note: none of this is specific to my case, it's just a generic example for a larger scenario) (注意:这都不是我的情况所独有的,这只是较大情况下的通用示例)

在我看来,您正在询问包含选项。

Section.includes(:posts, :user).find(1)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM