背景:ユーザーとコミュニティは
has_many:through
関係。各コミュニティには、それを識別する「community_type」文字列があります(つまり、「Gender」、「City」など)。
目的:編集フォームで、ユーザーがコミュニティタイプに基づいて:community_idsを編集できるようにします。何かのようなもの:
<%= form_for current_user do |f| %> <%= f.collection_select(:community_ids, Community.filtered_by("Gender"), :id, :name) %> <%= f.collection_select(:community_ids, Community.filtered_by("City"), :id, :name) %> <% end %>
問題は、フォームが:community_idsの最後のフォームフィールド値(この場合は「City」)のみを受け入れることであり、それらすべてを1つの大きな:community_ids配列としてマージするのではありません。
解決:
興味のある人のために、私はモデルコードを以下の答えからこれにリファクタリングすることになりました:
%W[ community1 community2 community3 community4 ].each do |name|
define_method "#{name}" do
self.communities.filtered_by("#{name}").map(&:name)
end
define_method "#{name}_ids" do
self.communities.filtered_by("#{name}").map(&:id)
end
define_method "#{name}_ids=" do |val|
self.community_ids += val
end
end