大量借用:
https://github.com/heroku/hstore_example
我可以在创建新模型时从New视图定义任意数量的“params”(我的hstore列),并正确设置hstore列并保存模型。完美!!
然而,当我尝试编辑并提交我的时候:
为param`id'
预期Hash(得到字符串)其中'id'是我给我创建的“param”的hstore键的名称。
同样有趣......我可以从控制台创建和更新相同的模型没问题。
WTF?!?
这是我的模特:
class Testmethod < ActiveRecord::Base
attr_accessible :name, :params
serialize :params, ActiveRecord::Coders::Hstore
def as_json(options = {})
{ :name => name, :params => params }
end
end
以下是表格:
<%= form_for(@testmethod) do |f| %>
<% if @testmethod.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@testmethod.errors.count, "error") %> prohibited this testmethod from being saved:</h2>
<ul>
<% @testmethod.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :name %>
<%= f.text_field :name %>
</div>
<div class="field">
<%= f.label :script %>
<%= f.text_area :script, :rows => 6 %>
</div>
<h4>Parameters</h4>
<div class="well">
<div class='clearfix attributeContainer'>
<div class='row'>
<p class='span3 underline'>Name</p>
<p class='span3 underline'>Value</p>
</div>
<% @testmethod.params.try(:each) do |key, value| %>
<div class="row">
<p class='span3'>
<%= text_field_tag key, key, :class => 'text_field dynamicAttributeName' %>
</p>
<p class='span3'>
<%= text_field key, :class => 'text_field', :value => value %>
</p>
<p class='span1'>
<a herf='#' class='btn removeRow'>X</a>
</p>
</div>
<% end %>
<div class='row attributeTemplate <%= 'hide' if @testmethod.params.present? %>'>
<p class='span3'>
<input class='text_field dynamicAttributeName' id='' name='' placeholder='New Attribute name' size='30' type='text' />
</p>
<p class='span3'><input class='text_field' id='bar' name='' placeholder='value' size='30' type='text' /></p>
<p class='span1'><a herf='#' class='btn removeRow'>X</a></p>
</div>
<%= link_to 'Add Parameter', '#', :class => 'btn addAttribute btn-mini' %>
</div>
</div>
<div class="row">
<div class="span12">
<div class="actions">
<%= f.submit "Save", :class => 'btn btn-primary ' %> or <%= link_to "Cancel", request.referrer || testmethods_path %>
</div>
</div>
</div>
<% end %>
<%= content_for :js do %>
<script type='text/javascript'>
$('.attributeContainer').delegate('.dynamicAttributeName', 'keyup', function(event){
nameElem = $(this);
valueElem = nameElem.closest('.row').children('p').children('.text_field')
value = nameElem.val().toLowerCase();
valueElem.attr('id', 'testmethod_params_' + value );
valueElem.attr('name', 'testmethod[params][' + value + ']');
valueElem.attr('placeholder', 'value for ' + value );
})
$('.attributeContainer').delegate('.removeRow', 'click', function(){
console.log($(this).closest('.row'))
$(this).closest('.row').html('');
})
$('.addAttribute').on('click', function(){
contents = "<div class='row'>" + $('.attributeTemplate').html() + '</div>';
$(this).before(contents);
})
</script>
<% end %>