我一辈子都弄不明白,但这是我的模型:
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
所以我有一个连接表,我正在尝试制作一个表单,它会选中用户选择的商店名称旁边的复选框(此信息将来自连接表关系)并打开复选框剩余商店(来自商店模型)。我如何在 View 中显示它/使其在 Controller 中也能工作。我会改用集合吗? (我正在使用 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 %>
存储 Controller :
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 %>
关于ruby-on-rails - 连接表关系的简单表单复选框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39309363/