我有以下型号:
class Individual < ActiveRecord::Base
has_many visits
has_many cities, :through => visits
accepts_nested_attributes_for :visits, reject_if: proc { |a| a[:city_id].blank? }, allow_destroy: true
end
class Visit < ActiveRecord::Base
belongs_to individual
belongs_to city
end
class City < ActiveRecord::Base
has_many visits
has_many individuals, :through => visits
end
我正在尝试为每个人开发一个表格,列出我数据库中的所有城市,并允许他们勾选他们访问过的城市,然后添加一些关于该城市的基本属性。我目前拥有的是:
<%= form_for(individual) do |f| %>
<% for city in cities.each do %>
<tr>
<td>
<%= check_box_tag "individual[visits_attributes][][city_id]", city_id.id, individual.cities.include?(city) %>
</td>
<td>
<label>How good was your visit here?</label>
<%= select_tag "individual[visits_attributes][][sentiment]", options_for_select([ ...... ])) %>
</td>
<td>
<label>What was the weather like?</label>
<%= select_tag "individual[visits_attributes][][weather]", options_for_select([ ...... ])) %>
</td>
<td>
<label>Where did you stay?</label>
<%= select_tag "individual[visits_attributes][][accomodation]", options_for_select([ ...... ])) %>
</td>
</tr>
<% end %>
<%= f.submit "Update", :class => "btn" %>
<% end %>
这是一种工作方式,但它只是感觉不对劲而且不正常。此外,它会创建重复记录,我还无法让它删除记录。
任何人都可以提出更好的方法吗?或者帮我重构我已经拥有的东西?