accepted_nested_attributes_for with has_many polymorphic

时间:2012-12-24 05:19:03

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

我使用paperclip上传附加到studentcourseassignment的多文件,但我失败了。

模型

class StudentCourseAssignment < ActiveRecord::Base
    attr_accessible :score, :comment, :finish_status,:attachments
    accepts_nested_attributes_for :attachments
    belongs_to :assignment
    belongs_to :user
    has_many :attachments ,:as => :attachmentable,:dependent => :destroy
end

class Attachment < ActiveRecord::Base
    attr_accessible :user_upload 
    belongs_to :attachmentable , :polymorphic => true
    has_attached_file :user_upload
end

控制器

**new**

    @sca = StudentCourseAssignment.new 
    @sca.attachments.build
    @sca.attachments.build

**create**

    @sca = StudentCourseAssignment.new(params[:student_course_assignment])
    @assignment = Assignment.find(params[:assignment_id])
    @sca.user = current_user
    @sca.assignment = @assignment
    if @sca.save
        flash[:alert] = "success"
        redirect_to course_years_path
    else
        flash[:alert] = "fail"
        redirect_to course_years_path
    end

**查看**

<%= form_for @sca, :url => assignment_student_course_assignments_path(@assignment),
:html => { :id => 'student-assignment-form', :multipart => true } do |f| %>
file:
<%= f.fields_for :attachments do |a_f| %>
<%= a_f.file_field :user_upload %>
<%= submit_tag "create" %>
<% end%>
<% end %>

No association found for name `attachments'. Has it been defined yet?

如果删除accepts_nested_attributes_for:附件,它仍然是错误的

Attachment(#70201401779680) expected, got Array(#70201383294620)

希望你的帮助!thx!

2 个答案:

答案 0 :(得分:2)

更改

从:

attr_accessible :score, :comment, :finish_status,:attachments

为:

attr_accessible :score, :comment, :finish_status,:attachments_attributes

答案 1 :(得分:1)

我意识到这是一个老问题,但我认为你需要移动

accepts_nested_attributes_for :attachments

出现在

之后

has_many :attachments, :as => :attachmentable,:dependent => :destroy

我曾经在一个项目中遇到过这个问题;非常肯定它归结为accepts_nested_attributes_for期望在调用之前已经声明了关系。