【问题标题】:How to retrieve data from default rails :data hash?如何从默认 Rails 中检索数据:数据哈希?
【发布时间】:2016-11-21 10:38:59
【问题描述】:

我有这样的东西(基本下拉菜单):

<ul class="dropdown-menu">
   <% @sidebar_categories.each do |category| %>
     <li data-toggle="modal" data-target="#howtoFormModal">
       <%= link_to category.title, "#", :data => { :id => category.id } %>
     </li>
    <% end %>
 </ul>

我有一个位于模态框内的表单

<%= simple_form_for @howto, url: category_howtos_path(@category) do |f| %>
  #whatever here...
<% end %>

我想获取我之前在默认 rail :data hash 中传递的 id 并将 id 放入表单 url category_howtos_path(id will go here)

请问我该怎么做?

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-4 link-to


    【解决方案1】:

    我不能 100% 确定您要达到的目标,但也许您可以使用查询字符串,docs on link_to 提供了如何做到这一点的示例。

    所以在你的例子中是这样的:

    <ul class="dropdown-menu">
       <% @sidebar_categories.each do |category| %>
         <li data-toggle="modal" data-target="#howtoFormModal">
           <%= link_to category.title, some_path(id: category.id) %>
         </li>
        <% end %>
     </ul>
     # Which has an output like this
    
    <a href="/some-path?id=1">Category Title</a>
    

    那么……

    <%= simple_form_for @howto, url: category_howtos_path(params[:id]) do |f| %>
      #whatever here...
    <% end %>
    

    编辑

    通过第一个 sn-p 中 li 上的属性,您希望在单击时切换模式,然后在 simple_form_for URL 参数中具有切换模式的 id。问题是 category_howtos_path 在 ruby​​ 页面加载之前已被评估。因此,如果您想更改该 URL,您可能需要使用 javascript。所以也许在 javascript 中加载模式并有一个事件回调。

    用 JS sn-p 编辑

    是的,我已经尝试过了,但也许我做错了。

     $('#howtoFormModal').on('show.bs.modal', function (e) {
    
          //but I think that the JS will give a lot due to the rails loop 
          var categoryId = $("#li-id").data('id')
    
          // just to show the id on the modal
          $('#howtoFormModalLabel').val(categoryId); 
     });
    

    你会想要获取你点击的元素的 id,所以

     $('#howtoFormModal').on('show.bs.modal', function (e) {
    
      // The categoryId from here needs to be from the clicked on element 
      var categoryId = $(e.relatedTarget).data('id')
    
      // just to show the id on the modal
      $('#howtoFormModalLabel').val(categoryId); 
    

    });

    【讨论】:

    • 这是过去的样子,因为之前它是不同页面上的表单。但是现在它在一个模态中,所以没有必要再去不同的页面了。谢谢你的建议
    • 如果你用你的 js 代码更新你的问题,我也许能帮上忙?
    • 我已经用你的 js 编辑更新了我的答案。 e.relatedTarget 是代表您单击的li 的元素。这应该会为您提供数据属性。
    • 它不起作用。所以从这里开始要么我打错了一些东西(我相信你知道我在说什么作为一个程序员 XD)或者我在引导模式上使用了错误的事件但只有 2 个(show.bs.modal 和 shown.bs .modal)。你帮我看看我的问题出在哪里:得到我点击的 elmt,谢谢。我会尝试这样的事情:stackoverflow.com/questions/8903992/… 并适应它。
    猜你喜欢
    • 1970-01-01
    • 2019-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-29
    • 1970-01-01
    • 2012-05-06
    相关资源
    最近更新 更多