簡體   English   中英

只需一次數據庫調用即可將多個表中的數據存儲在一個變量中(Rails)

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

假設這些模型:

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

假設此控制器:

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

最后是這個視圖:

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

我的問題:

這將導致我在視圖中針對每個循環的each循環在聲明的postuser變量中進行多個數據庫調用。

有我包括所有和唯一的信息,我需要對上面的代碼與一個單一的數據庫調用工作,並將其存儲在一個方式@sections變量(我假設這將與加入工作)。

換句話說,我想將此信息存儲在單個數據庫調用的@sections變量中:

  • 部分name
  • 部分的updated_at
  • 部門的position
  • 部分用戶的username
  • 部分用戶的url_for
  • 該部分的帖子name
  • 部分帖子的url_for

我將如何訪問這些信息?

(注意:這都不是我的情況所獨有的,這只是較大情況下的通用示例)

在我看來,您正在詢問包含選項。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM