连接表关系的简单表单复选框

rav*_*711 2 ruby-on-rails simple-form

我一生都无法弄清楚这一点,但这是我的模型:

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
Run Code Online (Sandbox Code Playgroud)

所以我有一个连接表,我正在尝试制作一个表单,它会选择用户选择的商店名称旁边的复选框(此信息将来自连接表关系)并打开其余商店的复选框(来自商店模型)。我如何在视图中显示/使其在控制器中也能工作。我会改用集合吗?(我正在使用 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 %>
Run Code Online (Sandbox Code Playgroud)

存储控制器:

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

max*_*max 5

当您在 rails 中设置一对多或多对多关系时,模型会获得一个_idssetter:

User.find(1).store_ids = [1,2,3]
Run Code Online (Sandbox Code Playgroud)

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

内置的 Rails集合表单助手利用了这个:

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

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

SimpleForm 有关联助手,可以添加更多的糖。

<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 %>
Run Code Online (Sandbox Code Playgroud)