I have this relations:
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
I can CRUD communities, but i've been searching how to in the controller/view add many people to that community, then show them but i can't find and answer.
I'll really appreciate your help!
The simplest way is by using the 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
But I would try to go with a less awkward and more descriptive naming scheme like:
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.