[英]Accessing another table's attributes with a foreign key and belongs_to association
[英]ruby on rails 4 foreign key and association to access another table's attributes
问题是如何列出与每个项目关联的所有资产?
到目前为止,这里是:我有一个项目模型和资产模型。 一个项目可以有很多资产(通过载波上传)
这是project.rb
class Project < ActiveRecord::Base
validates :title, length: { maximum: 150 } ,uniqueness: true, presence: true
has_many :assets
end
这是asset.rb
class Asset < ActiveRecord::Base
mount_uploader :attachment, AttachmentUploader
belongs_to:project
end
在project_controller.rb的索引方法中,我具有以下实例变量:
class ProjectsController < ApplicationController
def index
@projects = Project.all
@assets = Asset.all
end
def project_params
params.require(:project).permit(:title,assets_attributes: [:id,:project_id,:attachment])
end
end
这是视图index.html.erb,其中列出了所有资产,而不是与项目关联的资产
<% @projects.each do |project| %>
<td><%= project.title %></td>
<% @assets.each do |asset| %>
<td><%= asset.attachment.size %></td>
<% end %>
<% end %>
您的视图应如下所示:
<% @projects.each do |project| %>
<td><%= project.title %></td>
<% project.assets.each do |asset| %>
<td><%= asset.attachment.size %></td>
<% end %>
<% end %>
不要忘记从控制器中删除@assets = Asset.all
,并考虑添加分页。
另外,为了避免在您的视图中出现N + 1个查询,您可以
@projects = Project.includes(:assets) # you dont need .all, I think it's deprecated in rails 4 when you use it this way
在您的控制器中。 这将在1个查询中加载所有需要的项目。
而且,如果您只需要资产的size属性,则可以执行以下操作以使其更有效:
@projects = Project.includes(:assets).select('projects.*, assets.size').references(:assets)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.