基于params的Carrierwave删除方法

时间:2015-09-29 07:32:34

标签: ruby-on-rails ruby carrierwave

我的模型中有多个Carrierwave附件字段,我希望能够在我的节目视图中删除。由于有多个字段,我将参数传递给我的控制器方法,因此它知道要删除哪个文件:

def remove_attachment
  post = Post.find(params[:id])
  post["remove_#{params[:attachment]}!"]
  post.save
  redirect_to post
end

但是,以下行无效post["remove_#{params[:attachment]}!"]?不知道我在哪里错了?

我测试过以下哪项有效:

def remove_attachment
  post = Post.find(params[:id])
  post.remove_compliance_guide! # one of the attachment fields
  post.save
  redirect_to post
end

我意识到我可以在下面做,但我认为我的第一个解决方案更清洁。

def remove_attachment
  post = Bid.find(params[:id])

  if params[:attachment] == 'compliance_guide'
    post.remove_compliance_guide!
  elsif params[:attachment] == 'compliance_other'
    post.remove_compliance_other!
  elsif params[:attachment] == 'compliance_agreement'
    post.remove_compliance_agreement!
  end
  post.save
  redirect_to post
end  

以防我在其他地方犯了错误:

路线:post 'posts/:id/remove_attachment', to: 'posts#remove_attachment'

查看链接:link_to 'Remove', { controller: 'post', action: "remove_attachment", attachment: 'compliance_guide', id: @post.id }, method: 'post', class: "file-remove right"

1 个答案:

答案 0 :(得分:2)

您可以使用send通过将其名称作为字符串传递来调用方法:

def remove_attachment
  post = Post.find(params[:id])
  post.send("remove_#{params[:attachment]}!")
  post.save
  redirect_to post
end

请注意,如果附件不存在,则会引发NoMethodError。你可以使用类似的东西解决这个问题:

if post.respond_to?("remove_#{params[:attachment]}!")
  post.send("remove_#{params[:attachment]}!")
  post.save
end