【问题标题】:Forms and Rails Select and Image Galleries How Would You Do It?Forms and Rails Select 和 Image Gallery 你会怎么做?
【发布时间】:2015-10-09 01:24:14
【问题描述】:

所以我正在构建一个用户填写表格的应用程序。我希望表单问题的答案之一是用户可以选择来回答该特定问题的图像库。类似于 Image Picker gem。

<select class="image-picker show-labels show-html">
    <option data-img-src="http://placekitten.com/220/200" value="1">Cute Kitten 1</option>
    <option data-img-src="http://placekitten.com/180/200" value="2">Cute Kitten 2</option>
    <option data-img-src="http://placekitten.com/130/200" value="3">Cute Kitten 3</option>
    <option data-img-src="http://placekitten.com/270/200" value="4">Cute Kitten 4</option>
</select>

我对这个潜在的解决方案有两个问题。

  1. 我想在显示和索引页面上显示图像的名称,而不是整数值。在这种情况下,有没有办法传递描述而不是整数?我可以构建一个模型并使用 collection_select 然后调用 name 方法,但是如何将图像 url 输入到模型中,以便它像上面的 HTML 一样被正确调用和显示?

  2. 我有大约 200 张图像我想这样做。有没有更简单的方法来实现这一点,还是我需要从控制台手动将每个条目输入到模型中?

谢谢!

【问题讨论】:

    标签: ruby-on-rails forms select collections


    【解决方案1】:

    我想在“显示”和“索引”页面上显示图像的名称, 不是整数值

    这取决于您加载图像的方式,以及加载图像的全部数据。

    您似乎已经知道使用 Paperclip 之类的东西的优点和缺陷,或者甚至只是使用 model 并将数据保存在里面。

    --

    我会亲自使用对 URL 的简单引用来填充模型:

    #app/models/image.rb
    class Image < ActiveRecord::Base
       #columns id | name | url | description | created_at | updated_at
    end
    

    您可以调用以下命令:

    f.select :image_id, options_for_select(@images.map{ |i| [i.name, i.id, {'data-img-src'=>c.url}] })
    

    options_for_selectsupports custom data attributes 供您选择; collection_select 目前好像不支持。

    除此之外,我不确定您要实现的功能。


    从控制台手动将每个条目输入到模型中?

    您可能正在寻找seeds functionality of Rails

    #db/seed.rb
    images = [
     {url: "url1", name: "name", description: "kitty"},
     {url: "url2", name: "name", description: "kitty"}
     # this has to be manual unless you pull it from a CSV or something
    ]
    
    images.each do |img|
       Image.find_or_create_by(url: img.url, name: img.name, description: img.description)
    end
    

    然后您可以使用以下命令将其关闭:

    $ rake db:seed
    

    这将使用您放入seed.rb 文件的任何内容填充您的数据库。应该会为您节省很多时间!

    【讨论】:

    • 谢谢,里奇。说得通。感谢您的帮助!
    • Rich,当我运行 rake db:seed 时出现错误:“NoMethodError: undefined method `url' for #<0x007f81a428bec8>
    【解决方案2】:

    Rich 的解决方案有效,但您还需要添加此 javascript 以使其发挥作用:

    $(document).ready(function(){ 
    $("select").imagepicker({
      hide_select:  true, 
      show_label:   true,
      clicked:function(){
    
        console.log($(this).find("option[value='" + $(this).val() + "']").data('img-src'));
    
          }
        });
     });    
    

    【讨论】:

      猜你喜欢
      • 2022-12-28
      • 1970-01-01
      • 1970-01-01
      • 2010-09-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-15
      • 2011-07-20
      相关资源
      最近更新 更多