首页 > 解决方案 > 通过 javascript 接收 Carrierwave URL

问题描述

有没有办法通过 sql 或 javascript 来获取 Model.image_url ?

我有一个选择,当更改时,我希望<img src=>动态更改。

在其他情况下,我执行了以下操作来更改 div 容器的背景颜色:

<%= f.grouped_collection_select :color_id, @other_model, :colors, :title, :id, :title, include_blank: "Select Color" %>

<div id="div" style="background-color:<%= "#{model.color.hex}" %>;">
...
</div>

**javascript**

var colors = <%= Color.pluck(:id, :hex).to_h.to_json.html_safe %>;
document.getElementById("model_color_id").addEventListener("change", function(){
    document.getElementById("div" %>").style.backgroundColor = colors[this.value];
}, false);

为了获得载波图像,我尝试了类似的方法:

var product_mock = <%= Item.pluck(:id, :image).to_h.to_json.html_safe %>;
    document.getElementById("model_item_id").addEventListener("change", function(){
        document.getElementById("item").src = product_mock[this.value];
}, false);

但这并没有抓住*.url'or*_url

尝试了这样的方法onchange

$('#shop_product_item_id').on('change', function(){
    let item_id = $(this).val(); #tried with and without these 2 lines and with var
    console.log(item_id); #tried with and without these 2 lines
    var image = <%= Item.find(1).image_url %>;
    document.getElementById("id").src = image;
});

有一个id:1

没有任何东西打印到控制台,但出现以下错误:

Uncaught TypeError: e.unique is not a function

有没有办法从carrierwave thorugh sql甚至javascript中的ruby中获取这个?

标签: javascriptsqlruby-on-railsrubycarrierwave

解决方案


您可以将代码更改Item.pluck(:id, :image).to_h.to_json.html_safeItem.all.map{|item| [item.id, item.image_url]}.to_h.to_json.html_safe. 但正如其他人在评论中所说,最好通过 Ajax 请求获取项目,而不仅仅是将它们存储在 html 中。


推荐阅读