将文本字段中的图像包装到image_tag中

时间:2022-11-29 12:15:03

I would like to create a helper or change the model.rb to behave like:

我想创建一个帮助器或更改model.rb以表现如下:

Post model has a text field, which contains urls, all separated with new lines. On create or update, rails scans this field, when it finds url like:

Post model有一个文本字段,其中包含url,全部用新行分隔。在创建或更新时,rails会在找到url时扫描此字段:

http://i.imgur.com/imanimage.png
http://i.imgur.com/anotherimage.png

Then it leaves them as is, but in the show action it renders them as:

然后它保持原样,但在show动作中它将它们呈现为:

= image_tag('http://i.imgur.com/imanimage.png', class: 'my-image-class')
= image_tag('http://i.imgur.com/anotherimage.png', class: 'my-image-class')

Probably a helper method could do this.

可能一个辅助方法可以做到这一点。

2 个解决方案

#1


0  

Does the text field store anything else but the urls? If it does, you should consider creating helper using regex to get all urls and change these to <img src=''/>,

除了网址外,文本字段是否还存储了其他内容?如果是这样,你应该考虑使用正则表达式创建帮助以获取所有URL并将其更改为将文本字段中的图像包装到image_tag中

If not, you can use in haml/erb file.

如果没有,您可以在haml / erb文件中使用。

Model.text.each_line do |m| 
  image_tag(m, class: 'my_img') 
end 

Reference: http://ruby-doc.org/core-2.1.0/String.html#method-i-lines

参考:http://ruby-doc.org/core-2.1.0/String.html#method-i-lines

#2


0  

If you're saving these URLs in your database, you it should be quite a simple procedure:

如果您要在数据库中保存这些URL,那么它应该是一个非常简单的过程:

#app/models/image_url.rb
Class ImageURL < ActiveRecord::Base
end

#app/controllers/image_urls_controller.rb
def show
    @url = ImageURL.find(params[:id])
end

#app/views/image_urls/show.html.erb
<%= image_tag(@url, class: 'my-image-class')

If you add some more context to your question, I'll be able to give you a more refined answer!

如果您在问题中添加更多上下文,我将能够为您提供更精确的答案!

#1


0  

Does the text field store anything else but the urls? If it does, you should consider creating helper using regex to get all urls and change these to <img src=''/>,

除了网址外,文本字段是否还存储了其他内容?如果是这样,你应该考虑使用正则表达式创建帮助以获取所有URL并将其更改为将文本字段中的图像包装到image_tag中

If not, you can use in haml/erb file.

如果没有,您可以在haml / erb文件中使用。

Model.text.each_line do |m| 
  image_tag(m, class: 'my_img') 
end 

Reference: http://ruby-doc.org/core-2.1.0/String.html#method-i-lines

参考:http://ruby-doc.org/core-2.1.0/String.html#method-i-lines

#2


0  

If you're saving these URLs in your database, you it should be quite a simple procedure:

如果您要在数据库中保存这些URL,那么它应该是一个非常简单的过程:

#app/models/image_url.rb
Class ImageURL < ActiveRecord::Base
end

#app/controllers/image_urls_controller.rb
def show
    @url = ImageURL.find(params[:id])
end

#app/views/image_urls/show.html.erb
<%= image_tag(@url, class: 'my-image-class')

If you add some more context to your question, I'll be able to give you a more refined answer!

如果您在问题中添加更多上下文,我将能够为您提供更精确的答案!