2013-06-11 53 views
0

我想创建一个表单,允许一个组选择他们可以在系统中使用的多个模块。不幸的是每次我尝试这个时,我都会收到一些疯狂的关联错误,我不知道为什么。用has_many关系创建表单ruby

这里是我的形式

<%= form_for @group, :url => admin_groups_path, :html => { :class => 'entry' } do |f| %> 
    <%= render :partial => 'shared/error_messages', :locals => { :object => @group } %> 

    <div class="g12"> 
    <fieldset> 
     <fieldset> 
     <legend>Add Group</legend> 
     <div class="simple_format"> 
      <section class="g3"> 
      <%= f.label :name %> 
      <div><%= f.text_field :name, :size => 15 %></div> 
      </section> 
      <section class="g3"> 
      <%= f.label :is_facility, 'Facility?' %> 
      <div style="display:block;margin: 0 auto;width:25px;"><%= f.check_box :is_facility %></div> 
      </section> 
      <section class="g3"> 
      <%= f.label :parent_id %> 
      <div style="display:block;margin: 0 auto;width:25px;"><%= f.collection_select :parent_id, current_group.self_and_descendants.reject(&:is_facility), :id, :name %></div> 
      </section> 
      <section class="g3"> 
      <%= f.label :time_zone, 'Time Zone' %> 
      <div><%= f.select :time_zone, ActiveSupport::TimeZone.all.map(&:name).select {|x| x=~ /US/} %></div> 
      </section> 
     </div> 
     <div class="simple_format"> 
      <section class="g3"> 
      <%= f.label :federal_tax_number, 'Federal Tax ID' %> 
      <div><%= f.text_field :federal_tax_number, :size => 15 %></div> 
      </section> 
      <section class="g3"> 
      <%= f.label :national_provider_identifier, 'National Provider ID' %> 
      <div><%= f.text_field :national_provider_identifier, :size => 15 %></div> 
      </section> 
      <section class="g3"> 
      <%= f.label :modules, 'Allowed Modules' %> 
      <div><%= f.collection_select :group_access_modules, AccessModule.all, :id, :name, {}, {:multiple => true} %></div> 
      </section> 
     </div> 
     <section class="g12"> 
      <div><%= f.submit "Add Group", { :class => 'form-submit' } %></div> 
     </section> 
     </fieldset> 
    </fieldset> 
    </div> 
<% end %> 

下面的代码是我的模型

class Group < ActiveRecord::Base 
    has_many :group_access_modules 
end 

以下是错误我得到保存

<h1> 
    ActiveRecord::AssociationTypeMismatch 
    in Admin::GroupsController#create 
</h1> 
<pre>GroupAccessModule(#70245162706560) expected, got String(#70245155065480)</pre> 

我完全失去了现在。

+0

请发布您的GroupsController代码。 – vee

回答

0

可以使用fields_for在你的表格的关联。它应该是这个样子:

<%= f.fields_for :group_access_modules do |g| %> 
    <%= g.collection_select(:group_id, AccessModule.all, :id, :name, {}, {:multiple => true} %> 
<% end %> 

注:这可能是必要的,如果你正在使用一种非常规的外键的名称改变方法(:group_id)。

0

您是否尝试过使用simple_form?它使得关联有很多关系很容易,例如:

<%= f.association :company %> 

显然,这会让你的代码更容易阅读,而且它是可配置的。

也有railscast on habtm checkboxes但这是一个修订的情节,我认为你需要订阅。

让我知道你在想什么的simple_form宝石