基于参数的载波去除方法
Carrierwave remove method based on params
我的模型中有多个 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:link_to 'Remove', { controller: 'post', action: "remove_attachment", attachment: 'compliance_guide', id: @post.id }, method: 'post', class: "file-remove right"
您可以使用 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
我的模型中有多个 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:link_to 'Remove', { controller: 'post', action: "remove_attachment", attachment: 'compliance_guide', id: @post.id }, method: 'post', class: "file-remove right"
您可以使用 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