无法使用carrierwave将文件上传到父表单ruby中的子模型

时间:2017-04-28 15:35:15

标签: ruby-on-rails ruby carrierwave

我已经被困2天,试图找出如何将带有carrierwave的文件上传到模型并将该模型附加到父模型。

class HandOut < ApplicationRecord
  belongs_to :course_post
  mount_uploader :attachment, AttachmentUploader
end

class HandOutsController < ApplicationController
  def new
    @handOut = HandOut.new
  end

  def create
    @handOut = HandOut.new(hand_out_params)
  end

  def destroy
  end

  private
  def hand_out_params
    params.require(:hand_out).permit(:attachment)
  end
end

这是父

的创建
def create
    @c = Course.find_by_id(params[:course_id])
    @coursePost = @c.course_posts.build(post_params)
    @coursePost.hand_outs.build(params[:attachment])
    if (@coursePost.save)
      redirect_to controller: 'courses', action: 'show', id: params[:course_id]
    end
  end
def post_params
    params.require(:course_post).permit( :course_id, :title, :content)
  end

这是表格

<%= form_for(@newPost, :html => { :multipart => true }) do |f| %>
    <%= hidden_field_tag(:course_id, @course.id) %>
    <div class= "field">
      <%= f.text_field :title %>
    </div>
    <div class= "field">
      <%= f.text_field :content %>
    </div>
    <div class= "field">
      <%= f.file_field(:attachment) %>
    </div>
    <div class= "actions">
      <%= f.submit "Post!" %>
    </div>
  <% end %>

此外,coursePost是在课程展示内创建的(课程内容为父母)

def show
    @posts = @course.course_posts.all
    @newPost = CoursePost.new
  end

这是coursePost模型

class CoursePost < ApplicationRecord
  belongs_to :course
  has_many :hand_outs
  validates :course_id, presence: true
  default_scope -> { order(created_at: :desc) }
end

谢谢你的帮助。

1 个答案:

答案 0 :(得分:0)

accepts_nested_attributes_for添加到CoursePost:

has_many :hand_outs
accepts_nested_attributes_for :hand_outs
validates :course_id, presence: true

以新邮箱形式fields_for

<%= f.fields_for :hand_outs do |h| %>
  <div class= "field">
    <%= h.file_field :attachment %>
  </div>
<% end %>

post_params更新为:

def post_params
  params.require(:course_post).permit(:course_id, :title, :content, hand_outs_attributes: [:attachment])
end

现在删除create method中的行:

@coursePost.hand_outs.build(params[:attachment])

我希望它有所帮助