ruby-on-rails - Rails 中包含 Dragonfly gem 图像的重复记录

标签 ruby-on-rails ruby-on-rails-3 dragonfly-gem

如何使用蜻蜓图像复制 ActiveRecord 对象?

我有以下内容。

型号:

class Event < ActiveRecord::Base

  image_accessor :thumbnail

  attr_accessible :thumbnail, :remove_thumbnail, :retained_thumbnail

  validates :thumbnail, presence: true
end

Controller :

def clone
  @event = Event.find(1).dup
  render :new
end

查看:

<%= form_for @event do |f| %>
  <%= f.label :thumbnail %>
  <%= image_tag(@event.thumbnail.thumb('100x75').url) %>
  <label><%= f.check_box :remove_thumbnail %> Remove?</label>
  <%= f.file_field :thumbnail %>
  <%= f.hidden_field :retained_thumbnail %>
<% end %>

当我渲染表单时,图像会显示,但在提交时,图像会被清除。

有一件事,我想确保它们实际上是不同的图像,因此如果我编辑原始记录,不会影响重复记录。

最佳答案

以下是我如何让它工作,覆盖对象的 dup 行为:

def dup
  target = Event.new(self.attributes.reject{|k,v| ["id", "attachment_uid"].include?(k) })
  target.attachment = self.attachment
  target
end

然后,当您在目标上调用save时,图像将被复制到新位置。

请注意,在第一行,我首先尝试了 target = super,以利用对象的默认 dup 行为,但这导致原始对象的文件被删除。上面的解决方案终于对我有用了。

关于ruby-on-rails - Rails 中包含 Dragonfly gem 图像的重复记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14754747/

相关文章:

ruby-on-rails - Capistrano: SSHKit::Command::失败:捆绑退出状态:1

javascript - 调用rails内的javascript函数hidden_​​field_tag

sql - Rails has_one 和 belongs_to 加入

ruby-on-rails - 在 Rails 中呈现 Action 时不显示警报

ruby-on-rails - rails : Show form from different model in a view

ruby-on-rails-3 - Rails 中的日期字段和文本输入

ruby-on-rails-3 - Rails 3 和 RefineryCMS - Dragonfly::Shell::CommandFailed in Refinery::Admin::ImagesController#create

ruby-on-rails - rails 3,如何在组中设置 user.role#create 操作

imagemagick - Centos 5.6 上的 Dragonfly、rails 3.2、Refinery Edge (2.0) ImageMagick