【发布时间】:2016-09-04 04:03:22
【问题描述】:
我这辈子都想不通,但这是我的模型:
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
所以我有一个连接表,我正在尝试制作一个表单,该表单将选中用户选择的商店名称旁边的复选框(此信息将来自连接表关系)并打开复选框剩余的商店(来自 Store 模型)。我如何在视图中显示/使其在控制器中也能正常工作。我会改用集合吗? (我正在使用 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
【问题讨论】: