简体   繁体   English

Rails视图/控制器has_many通过

[英]Rails view/controller has_many through

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. 我可以CRUD社区,但是我一直在搜索如何在控制器/视图中将许多人添加到该社区,然后向他们显示,但我找不到并回答。

I'll really appreciate your help! 非常感谢您的帮助!

The simplest way is by using the Rails form options helpers : 最简单的方法是使用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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM