Paperclip多文件上传

时间:2013-03-18 21:38:27

标签: ruby-on-rails ruby-on-rails-3 ruby-on-rails-3.2 paperclip

我有三种模式:

 class Project < ActiveRecord::Base
  attr_accessible :name
  has_many :tickets, dependent: :delete_all
 end

 class Ticket < ActiveRecord::Base
  belongs_to :project
  attr_accessible :description, :title,:asset  
  has_many :assets
  accepts_nested_attributes_for :assets
end

class Asset < ActiveRecord::Base
  attr_accessible :title, :body
  belongs_to :ticket
  has_attached_file :asset
end

_form:

<%= form_for([@project,@ticket], html: { multipart: true }) do |f| %>
<p>
    <%= f.label :title %>
    <%= f.text_field :title %>
</p>
<p>
    <%= f.label :description %>
    <%= f.text_area :description %>
</p>

<% number = 0 %>
<%= f.fields_for :assets do |asset| %>
    <p>
        <%= asset.label "File ##{number +=1}" %>
        <%= asset.file_field :asset %>
    </p>
<% end %>
<%= f.submit %>
<% end %>

TicketsController:

def new
 @ticket = @project.tickets.build
 3.times { @ticket.assets.build }
end

问题是当我尝试为项目创建新票证时,它在/ projects / 1 / tickets / new中显示ActiveRecord :: UnknownAttributeError 未知属性:ticket_id @ ticket = id:nil,title:nil,description:nil,project_id:1,created_at:nil,updated_at:nil,user_id:nil

从错误消息我可以看到门票“id”为零(尚未创建),因此资产没有ticket_id,那么我该如何解决呢?

2 个答案:

答案 0 :(得分:1)

attr_accessible :ticket_id

您需要将此字段添加为可在其模型上访问的attr。

对于嵌套的attribuetes 您还需要将project_assets添加为attr_accessibl / attr_accessor

attr_accessible :project_assets
attr_accessor :project_assets

答案 1 :(得分:0)

您应该将nested_form gem用于资产,并且您必须在资产数据库表中创建ticket_id的属性才能正常工作。