【问题标题】:Rails test for key in hstore columnRails 测试 hstore 列中的键
【发布时间】:2014-11-09 09:28:26
【问题描述】:

我有一个 Rails 4 应用程序,其中模型 Vehicle 有一个名为 data 的 hstore 列。该应用程序还使用gem 'acts_as_tenant'。模型Tenant 也有一个名为data 的hstore 列。

我正在做的是将用户定义的字段存储在车辆表的租户中。换句话说,如果租户数据 (hstore) 列包含“颜色”,那么我希望每辆车在其数据 (hstore) 列中都有相同的键。

这是 Vehicle 表单的代码:

   <% if current_tenant.data.present? %>
        <%= f.simple_fields_for :data do |d| %>
            <% current_tenant.data.each do |key, value| unless ???????@vehicle.data%>
                <div class="row">
                  <p class='col-md-3'>
                    <%= text_field_tag key, key, :class => 'text_field dynamicAttributeName' %>
                  </p>
                  <p class='col-md-3'>
                    <%= d.text_field key, :class => 'text_field', :value => value %>
                  </p>
                  <p class='col-md-1'>
                    <a herf='#' class='btn removeRow'>X</a>
                  </p>
                </div>
            <% end %>
        <%- end -%>
    <% end %>

    <% if @vehicle.data.present? %>
        <%= f.simple_fields_for :data do |d| %>
            <% @vehicle.data.each do |key, value| %>
                <div class="row">
                  <p class='col-md-3'>
                    <%= text_field_tag key, key, :class => 'text_field dynamicAttributeName' %>
                  </p>
                  <p class='col-md-3'>
                    <%= d.text_field key, :class => 'text_field', :value => value %>
                  </p>
                  <p class='col-md-1'>
                    <a herf='#' class='btn removeRow'>X</a>
                  </p>
                </div>
            <% end %>
        <%- end -%>
    <% end %> 

我的问题是&lt;% current_tenant.data.each do |key, value| unless ???????这一行

我不想添加相同的密钥两次。所以,如果 Vehicle 数据字段已经有color,我不想再添加它。

如何测试 Vehicle.data 字段以查看它是否具有等于 current_tenant.data.each do |key, value| 的键。

谢谢你的帮助!!!

【问题讨论】:

    标签: ruby-on-rails hstore


    【解决方案1】:

    正如您所见,在 Rails 模型上通过 store_accessor :data 定义的 hstore 列的核心就像哈希一样。

    您可以做一个简单的检查,看看 vehicle.data 哈希是否有您要查找的密钥。

    类似:

    current_tenant.data.each do |key, value|
      puts "#{key} => #{value}" unless vehicle.data.key?(key)
    end
    

    将打印键值对,除非车辆 hstore 列也具有相同的键

    【讨论】:

      猜你喜欢
      • 2014-07-18
      • 1970-01-01
      • 1970-01-01
      • 2014-03-17
      • 1970-01-01
      • 2016-09-01
      • 2012-11-25
      • 2017-08-07
      • 1970-01-01
      相关资源
      最近更新 更多