[英]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
循环在声明的post
和user
变量中进行多个数据库调用。
有我包括所有和唯一的信息,我需要对上面的代码与一个单一的数据库调用工作,并将其存储在一个方式@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.