考虑我有三个表用户,国家,州。我有一个添加新用户的页面,当我添加新用户时,我必须在选择框中列出国家,在选择国家时,多选框应该加载该国的状态,我应该能够选择所需的状态。
同样,我可以单击添加按钮添加另一个选择框并选择另一个国家并选择属于该国家的州,依此类推。而且我知道这需要嵌套属性和动态选择菜单功能,但不知道如何将它们一起使用。
以下是我尝试过的
楷模:
class Country < ActiveRecord::Base
has_many :states
attr_accessible :name
end
和
class User < ActiveRecord::Base
serialize :state_id
has_many :user_countries
accepts_nested_attributes_for :user_countries, :allow_destroy => true
has_many :state
attr_accessible :username, :user_countries_attributes
end
和
class State < ActiveRecord::Base
belongs_to :country
attr_accessible :name, :country_id
end
和
class UserCountry < ActiveRecord::Base
serialize :state_id
belongs_to :users
attr_accessible :country_id, :user_id, :state_id
end
下图也清楚地显示了我想要完成的事情
更新
<%= form_for(@user) do |f| %>
<% if @user.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@user.errors.count, "error") %> prohibited this user from being saved:</h2>
<ul>
<% @user.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :username %><br />
<%= f.text_field :username %>
</div>
<%= f.fields_for :user_countries do |country| %>
<%= render "user_country_fields", :f => country %>
<% end %>
<div class="add_variant"><%= link_to_add_fields "Add Country", f, :user_countries %></div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
更新1:
<div class="entry_field">
<label>Country :</label>
<div id="field_country">
<%= f.collection_select :country_id, Country.all, :id, :name, :prompt => 'Select Country' %>
</div>
<div id="field_state">
<%= f.collection_select :state_id, State.all, :id, :name, {:prompt => 'Select State'}, { :multiple => true } %>
</div>
<%= link_to_remove_fields "remove", f %></div>