繁体   English   中英

Rails视图/控制器has_many通过

[英]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.

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