【发布时间】:2014-08-06 13:43:18
【问题描述】:
问题是如何列出与每个项目关联的所有资产?
这是我目前所拥有的: 我有一个项目模型和资产模型。一个项目可以有很多资产(由载波上传)
这里是项目.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 %>
【问题讨论】:
-
你的问题到底是什么?
-
在我的索引文件中,我想要与每个项目关联的资产,使用此代码,我拥有每个项目的所有资产。我不知道如何添加 where 子句或条件来修复它。
-
您只需要
project.assets即可获取当前项目的资产。 -
嗯,我试过了,这就是我写在这里的原因,它会引发这个错误`未定义的方法
attachment' for #<Asset::ActiveRecord_Associations_CollectionProxy:0x007fed63e97e08> -
那么给出错误是个好主意。帮助我们帮助您;)
标签: ruby-on-rails ruby-on-rails-4 rails-activerecord foreign-key-relationship model-associations