Carrierwave:store_path 中的 model.id 错误

发布于 2024-12-04 19:58:01 字数 743 浏览 0 评论 0原文

我正在尝试编写一种方法来将给定网址中的图像存储在 ruby​​ 工作线程中。它随我的 Rails 应用程序一起提供,我在其中显示对象图像。这是我想到的:

@message = Message.create!
my_uploader = PhotoUploader.new
photo = open(image_url)
@message[:photo] = my_uploader.store!(photo)
@message[:photo] = my_uploader.filename
@message.save!

PhotoUploader:

def store_dir
  Rails.env.production? ? (primary_folder = "production") : (primary_folder = "test")
  "#{primary_folder}/media/#{model.id}" 
end

Message 类:

class Message < ActiveRecord::Base
  attr_accessible :content, :photo, :user_id
  mount_uploader :photo, PhotoUploader
end

model.id 在存储路径中返回错误。即使保存后模型也是nil,文件存储在#{primary_folder}/media

I'm trying to write a method to store an image from a given url, inside a ruby worker. It comes along my Rails app in which I display the object image. Here is what I've come up with:

@message = Message.create!
my_uploader = PhotoUploader.new
photo = open(image_url)
@message[:photo] = my_uploader.store!(photo)
@message[:photo] = my_uploader.filename
@message.save!

the PhotoUploader:

def store_dir
  Rails.env.production? ? (primary_folder = "production") : (primary_folder = "test")
  "#{primary_folder}/media/#{model.id}" 
end

the Message class:

class Message < ActiveRecord::Base
  attr_accessible :content, :photo, :user_id
  mount_uploader :photo, PhotoUploader
end

The model.id returns an error in the storage path. The model is nil even after saving it, and the file is stored in #{primary_folder}/media

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

笑看君怀她人 2024-12-11 19:58:01

我认为您没有从模型中调用 store! ,这就是 model.id 不起作用的原因,因为 modelnil

这可能会为你做:

@message = Message.create!
photo = open(image_url)
@message.photo = PhotoUploader.new
@message.photo.store!(photo)
@message.photo = @message.photo.filename
@message.save!

我在 Rails 控制台中尝试了这个,并且 @message[:photo].store!(photo) 给出了相同的错误,但@message.photo.store!(photo) 有效。

I think it's that you're not calling store! from the model, which is why model.id doesn't work, because model is nil

This will probably do it for you:

@message = Message.create!
photo = open(image_url)
@message.photo = PhotoUploader.new
@message.photo.store!(photo)
@message.photo = @message.photo.filename
@message.save!

I tried this out in the rails console, and @message[:photo].store!(photo) gave the same error, but @message.photo.store!(photo) worked.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文