如何使用来自另一个控制器的表单来设置具有 has_many 的值:Rails4 中的直通关系?

How to use a form from another controller to set a value that has a has_many :through relation in Rails4?

这是我目前的情况:

我有一个模型 :companies 和一个模型 :users(Devise)。一家公司可以通过第三种模式 :moderator_connections 拥有许多审核用户,反之亦然。对于 select 当前版主,我已将列 current_company(未引用)添加到模型 :users

我想在整个网站的主菜单下添加一个 dropdown_menu。通过从此菜单 selecting 当前公司,用户可以切换到该公司的内容。我试图通过在 application.html.erb 中的 <%= yield %> 上方渲染一个部分表单来做到这一点。 form 试图为 current_user 编辑 current_company 整数(通过将其更改为关联公司之一的 company_id),但我认为我什至没有接近解决它:(

这是我的亲戚。

/models/company.rb:

has_many :moderator_connections    
has_many :moderators, through: :moderator_connections, class_name: 'User', foreign_key: 'company_id'

/models/user.rb:

has_many :moderator_connections
has_many :moderated_companies, through: :moderator_connections, class_name: 'Company', foreign_key: 'user_id'

/models/moderator_connection.rb:

belongs_to :user
belongs_to :company

/layouts/application.html.erb:

<main>
    <div class="container">
        <%= render partial: "users/current_company_form" %>

        <%= render partial: "shared/message" %>

        <%= yield %>
    </div>
</main>

/users/_current_company_form.html.erb:

<% if user_signed_in? %>
<%= form_for edit_user_registration_path do |f| %>
    <div class="form-group">
      <%= f.collection_select :current_company, current_user.moderator_connections(:company_id), :name, :id,{ prompt: "Choose a company" } %>

      <%= f.hidden_field :current_company, :value => current_user.moderator_connections(:company_id) %>

    <div class="actions">
        <%= f.submit %>
    </div>
<% end %>

部分渲染已经出错,我收到以下错误(取决于我所在的页面):No route matches [POST] "/pages/welcome"

老实说,我不知道如何创建它(您可以从我的愚蠢尝试中得出结论)。谁能帮帮我?

我不太确定,但我认为这应该可行:

<% if user_signed_in? %>
<%= form_for current_user, url: edit_user_registration_path do |f| %>
    <div class="form-group">
      <%= f.collection_select(:current_company, current_user.moderated_companies, :id, :name, prompt: "Select a company") %>
    <div class="actions">
        <%= f.submit %>
    </div>
  <% end %>
<% end %>

如果可行,请告诉我!

更新

我认为你应该改为使用:

#user.rb
has_many :moderated_companies, through: :moderator_connections, source: :company

#company.rb
has_many :moderators, through: :moderator_connections, source: :user