I have a Rails 4 app where the model Vehicle
has an hstore column called data
. The app is also using gem 'acts_as_tenant'
. The model Tenant
also has an hstore column called data
.
What I'm doing is storing user defined fields in Tenant for the Vehicle table. In other words if the Tenant data (hstore) column contains 'color', then I want every Vehicle to have that same key in their data (hstore) column.
This is the code for the Vehicle form:
<% 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 %>
My issue is the line <% current_tenant.data.each do |key, value| unless ???????
I don't want to add the same key twice. So, if the Vehicle data field already has color
, I don't want to add it again.
How do I test the Vehicle.data field to see if it has a key equal to the current_tenant.data.each do |key, value|
.
Thanks for the help!!!
At its core, an hstore column defined on a Rails model via store_accessor :data
acts just like a hash does, as you've seen.
You could do a simple check to see if the vehicle.data
hash has the key you are looking for.
Something like:
current_tenant.data.each do |key, value|
puts "#{key} => #{value}" unless vehicle.data.key?(key)
end
would print the key value pair unless the vehicle hstore column also had the same key