无法通过备用模型中的回形针上传图像

时间:2013-11-22 17:06:01

标签: ruby-on-rails ruby paperclip

结构

我有一个 Image 表,许多其他表都有外键。我的 TeamMember 表格中有image_id对图片表的引用。

图片

class Image < ActiveRecord::Base
  belongs_to :user
  has_attached_file :asset

  validates :user_id, presence: true
end

TeamMember

class TeamMember < ActiveRecord::Base
  belongs_to :project
  belongs_to :user

  has_one :image, as: :attachable
  accepts_nested_attributes_for :image

  validates :project_id, presence: true
  validates :user_id, presence: true
  validates :image_id, presence: true
  validates :name, presence: true, length: { maximum:75 }
  validates :description, presence: true, length: { maximum: 255 }

  after_initialize :init

  def init
    self.removed = false if self.removed.nil?
  end
end

控制器

def create
  @pteam_member = TeamMember.new(team_member_params)
  @pteam_member.user_id = get_current_user.id

  if @team_member.save
    redirect_to action: :show, id: @team_member.id
  else
    set_project
    render action: :new
  end
end

def team_member_params
  params.require(:team_member).permit(:name, :description, :image, :project_id)
end

查看

<%= form_for @team_member, url: team_members_path(params[:project_id]), html: { multipart: true } do |f| %>
      <div class="form-group">
        <%= f.label :name %>
        <%= f.text_field :name, { class: "form-control" } %>
      </div>

      <div class="form-group">
        <%= f.label :description %>
        <%= f.text_area :description, { class: "form-control", rows: 6 } %>
      </div>

      <div class="form-group">
        <%= f.label :image, 'Photo' %>
        <%= f.fields_for :image_attributes do |image_fields| %>
          <%= image_fields.file_field :asset %>
        <% end %>
      </div>

      <div class="actions">
        <div class="btn-group">
          <button type="submit" class="btn btn-success">save <span class="glyphicon glyphicon-floppy-saved"></span></button>
        </div>
      </div>
  <% end %>

问题

无论我尝试什么,我都无法将:image作为:team_member的一部分进行保存。我收到 ActiveRecord :: AssociationTypeMismatch 错误:

  

图像(#70132078464480)预期,获得ActionDispatch :: Http :: UploadedFile(#70132082679240)

我哪里错了?我错过了什么,我是以错误的方式接近这个?

1 个答案:

答案 0 :(得分:3)

您需要将文件附加到与team_member关联的图像对象。你实际做的是尝试将文件直接关联到team_member作为图像关联 - 这是行不通的。由于您使用的是nested_attributes,因此只需修改请求格式即可解决此问题。而不是,

<%= f.file_field :image %>

使用此:

<%= f.fields_for :image_attributes do |image_fields| %>
  <%= image_fields.file_field :asset %>
<% end %>

并相应地修改您列入白名单的参数。