我有一个项目模型和资产模型。一个项目可以有很多资产(由Carrier wave上传)
这是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的index方法中,我有以下实例变量:
class ProjectsController < ApplicationController
def index
@projects = Project.all
@assets = @projects.assets.all
end
def project_params
params.require(:project).permit(:title,assets_attributes: [:id,:project_id,:attachment])
end
end
这是视图,index.html.erb
<% @assets.each do |p| %>
<td><%= number_to_human_size(p.attachment.size) %></td>
<% end %>
我有错误的未定义方法`assets&#39; for Project :: ActiveRecord_Relation:0x007fa60850dd08
答案 0 :(得分:1)
您尝试在assets
对象而不是ActiveRecord::Relation
实例上调用Project
,这就是您收到错误的原因。要修复它,你可以这样做:
@assets = Asset.all
或者,确保只获得与项目相关的资产:
@assets = Asset.joins(:project)