我有这种关系:
class Community < ApplicationRecord
has_many :community_people
has_many :people, :through => :community_people
end
class CommunityPerson < ApplicationRecord
belongs_to :community
belongs_to :person
end
class Person < ApplicationRecord
has_many :community_persons
has_many :communities, :through => :community_persons
end
我可以CRUD社区,但我一直在搜索如何在控制器/视图中添加许多人到该社区,然后显示它们但我无法找到并回答。
我真的很感谢你的帮助!
答案 0 :(得分:0)
最简单的方法是使用Rails form options helpers:
<%= form_for(@community) do |f| %>
...
<div class="field">
<%= f.label :person_ids %>
<%= f.collection_select :person_ids, multiple: true %>
</div>
<% end %>
class CommunityControllers
...
def community_attributes
params.permit(:foo, :bar, person_ids: [])
end
end
但我会试着采用一种不那么尴尬和更具描述性的命名方案,如:
class Community < ApplicationRecord
has_many :citizenships
has_many :citizens, through: :citizenships
end
class Citizenship < ApplicationRecord
belongs_to :community
belongs_to :citizen, class_name: "Person"
end
class Person < ApplicationRecord
has_many :citizenships, foreign_key: 'citizen_id'
has_many :communities, through: :citizenships
end