Ruby on rails 如何获取基本URL(例如。http://localhost:3000)我的Rails应用程序?
我使用回形针允许用户附加内容,然后我发送电子邮件并希望将文件附加到电子邮件中。我正在尝试读入该文件并将其作为附件添加,如下所示:Ruby on rails 如何获取基本URL(例如。http://localhost:3000)我的Rails应用程序?,ruby-on-rails,paperclip,attachment,Ruby On Rails,Paperclip,Attachment,我使用回形针允许用户附加内容,然后我发送电子邮件并希望将文件附加到电子邮件中。我正在尝试读入该文件并将其作为附件添加,如下所示: # models/touchpoint_mailer.rb class TouchpointMailer < ActionMailer::Base def notification_email(touchpoint) recipients "me@myemail.com" from "Touchpoint Customer Portal &l
# models/touchpoint_mailer.rb
class TouchpointMailer < ActionMailer::Base
def notification_email(touchpoint)
recipients "me@myemail.com"
from "Touchpoint Customer Portal <portal@touchpointclients.com>"
content_type "multipart/alternative"
subject "New Touchpoint Request"
sent_on Time.now
body :touchpoint => touchpoint
# Add any attachments the user has included
touchpoint.assets.each do |asset|
attachment :content_type => asset.file_content_type,
:body => File.read(asset.url)
end
end
end
#模型/接触点_mailer.rb
类TouchpointMailer接触点
#添加用户包含的任何附件
touchpoint.assets.each do| assets|
附件:content\u type=>asset.file\u content\u type,
:body=>File.read(asset.url)
结束
结束
结束
这给了我以下错误没有这样的文件或目录-/system/files/7/original/image.png?1254497688
,堆栈跟踪表示调用file.read
。当我访问show.html.erb
页面并单击指向图像的链接时,类似于http://localhost:3000/system/files/7/original/image.png?1254497688
,图像显示良好
如何解决此问题?通常
根url
应提供此功能
File.read需要的是文件路径,而不是url。如果正在生成图像,则应调用图像生成代码并返回生成图像的字节,而不是调用
文件。读取(…)
资产。url
返回文件的url。这通常是/system/classname/xx/xx/style/filename.ext
。你应该把它放在一个图像\u标签中
您需要asset.path
。它返回文件的完整路径,通常类似于/home/username/railsapp/public/system/classname/xx/xx/style/filename.ext
HTH.正如Ziggythe仓鼠所说:asset.url是生成的用于网页的url(这就是为什么要使用unix风格的目录斜杠,正如评论中指出的那样) asset.path应该为您提供文件的操作系统感知路径,但回形针也不需要这样做。 您只需要
:body=>asset
这样:
touchpoint.assets.each do |asset|
attachment :content_type => asset.file_content_type,
:body => asset
end
我不知道为什么这一行代码在网络上如此难以捉摸。看起来它应该是最前端和最中心的。我没有生成它们,我让用户上传它们并将它们存储在文件系统中,但是当我指定文件路径(通过asset.url方法)时,我收到一个错误,说它找不到文件;但是,当我链接到它时(例如,link_to asset.name,asset.url),它工作正常,我可以查看图像。尝试
File.read(File.join(Rails.root,“public”,asset.url))
(假设图像位于文件系统的public/system/files/…
。嗯,问题似乎是它在文件名后添加的字符串,尝试cwninja所说的,我会得到错误“Invalid argument”。有没有办法在文件后没有gobbeldygook的情况下获得文件的基本路径?asset.url.gsub(/\?*/,”)
作为一个快速解决方案?它一直工作得很好,直到我尝试在rails邮件程序中使用它,并且遇到了这个未定义的方法'env'for nil:NilClass
,所以它不能在任何地方都工作。据我所知,请求
对象在邮件程序中不存在。这就是为什么你必须为主机专门定义一个值的原因。不确定为什么会这样做投票?这是不安全的!用户设置了“HTTP_主机”头,恶意用户可以在提交请求时将其更改为他/她想要的任何内容。这可能意味着可以将密码重置链接发送到其他人的服务器,或者可以更改图像等。请勿使用此选项
request.env["HTTP_HOST"]