[英]Rails view/controller has_many through
我有這種關系:
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社區,但是我一直在搜索如何在控制器/視圖中將許多人添加到該社區,然后向他們顯示,但我找不到並回答。
非常感謝您的幫助!
最簡單的方法是使用Rails表單選項助手 :
<%= 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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.