我有一个项目模型和资产模型。一个项目可以有多个资产(通过Carrier wave上传)
这是项目。rb
class Project < ActiveRecord::Base
validates :title, length: { maximum: 150 } ,uniqueness: true, presence: true
has_many :assets
end
,这是资产。rb
class Asset < ActiveRecord::Base
mount_uploader :attachment, AttachmentUploader
belongs_to:project
end
在project_controller的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 %>
我有错误未定义的方法'资产'项目::ActiveRecord_Relation:0x007fa60850dd08
您尝试在ActiveRecord::Relation
对象上调用assets
而不是Project
实例,这就是您得到错误的原因。要修复它,可以这样做:
@assets = Asset.all
或者,确保您只获得与项目相关的资产:
@assets = Asset.joins(:project)