ユーザー、国、州の 3 つのテーブルがあるとします。新しいユーザーを追加するページがあり、新しいユーザーを追加するときに、選択ボックスに国をリストする必要があり、国を選択すると、複数の選択ボックスに国の州がロードされ、できるはずです目的の状態を選択します。
同様に、追加ボタンをクリックして別の選択ボックスを追加し、別の国を選択して、その国に属する州を選択することもできます。そして、これにはネストされた属性と動的選択メニュー機能が必要であることは知っていますが、これらを一緒に使用する方法はわかりません。
以下は私が試したものです
モデル:
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>