gpt4 book ai didi

ruby-on-rails - nokogiri 替换

转载 作者:数据小太阳 更新时间:2023-10-29 08:54:34 25 4
gpt4 key购买 nike

我正在解析 HTML 文档并尝试替换图像 src。当我在控制台中尝试它时,它似乎做了我想做的事情,但是在我的模型中它似乎没有保存它。现在,我不确定我正在做的事情是否与 Rails 中的保存方式有误(我正在尝试更新内容字段并用本地镜像替换外部图像)或者它是否使用 nokogiri,但它没有保存使用 set_attribute 方法的结果

它完美地完成了其余部分。

  before_save :replace_zemanta_images

def replace_zemanta_images
doc = Nokogiri::HTML(content)
unless doc.css('div.zemanta-img').blank?
doc.css('div.zemanta-img img').each do |img|
io = open(URI.parse(img[:src]))
if photos.find_by_data_remote_url(img[:src]).blank?
photo = photos.build(:data => io, :data_remote_url => img[:src])
img.set_attribute('src', photo.data.url(:original)) #doesn't work!
end
end
end
end

最佳答案

我假设 content 是您模型的一个属性。

当您执行 img.set_attribute 时,您正在更新 Nokogiri::XML::Element 对象中的属性,但这不会更新 的文本>内容

在方法的末尾,您需要添加如下内容:

self.content = doc.to_s

关于ruby-on-rails - nokogiri 替换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4712278/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com