加入 table 关系的简单表单复选框

Simple Form check box for join table relationship

我一辈子都弄不明白,但这是我的模型:

class User < ApplicationRecord
  has_many :user_stores
  has_many :stores, through: :user_stores        
end

class UserStore < ApplicationRecord
  belongs_to :user
  belongs_to :store
end

class Store < ApplicationRecord
  has_many :user_stores
  has_many :users, through: :user_stores
end

所以我有一个连接 table,我正在尝试制作一个表单,该表单会选中用户选择的商店名称旁边的复选框(此信息将来自连接 table 关系)并打开其余商店的复选框(来自商店模型)。我如何在 view/make 中显示它在控制器中也能正常工作。我会改用集合吗? (我正在使用 Devise 和 Simple Form gem)

这是我目前拥有的:

<h1>Add Favorite Stores</h1>
<%= simple_form_for(@user, html: { class: 'form-horizontal' }) do |f| %>
  <%= f.fields_for :stores, @user.stores do |s| %>
    # not sure if this is the right way or not
  <% end %>
  <%= f.button :submit %>
<% end %>

店长:

class StoresController < ApplicationController
...
  def new
    @user = current_user
    @stores = Store.all
    # @user.stores => shows user's stores (from join table)
  end
end

当您在 rails 中建立一对多或多对多关系时,模型会得到 _ids setter:

User.find(1).store_ids = [1,2,3]

例如,这将在用户 1 与 ID 为 1,2 和 3 的商店之间建立关系。

内置的Rails collection form helpers利用这个:

<%= form_for(@user) do |f| %>
  <% f.collection_check_boxes(:store_ids, Store.all, :id, :name) %>
<% end %>

这会为每家商店创建一个复选框列表 - 如果存在关联,则它已经被选中。请注意,我们没有使用 fields_for,因为它不是嵌套输入。

SimpleForm has association helpers 添加更多的糖。

<h1>Add Favorite Stores</h1>
<%= simple_form_for(@user, html: { class: 'form-horizontal' }) do |f| %>
  <%= f.association :stores, as: :check_boxes %>
  <%= f.button :submit %>
<% end %>