【问题标题】:Simple Form check box for join table relationship连接表关系的简单表单复选框
【发布时间】: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

【问题讨论】:

    标签: ruby-on-rails simple-form


    【解决方案1】:

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

    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 %>
    

    【讨论】:

    • 非常感谢!你是救命稻草!
    • 我有一个后续问题:如何让路线变得安静?现在我正在为用户使用设计,root 'home#index' 资源:用户做资源:存储结束。当用户登录时,他们会转到 Home 控制器。然后,当检查最喜欢的商店时,他们会转到 Stores 控制器,但现在使用上面的表格,他们会转到 Users 控制器,因为它正在更新用户。那是对的吗?当用户去最喜欢的商店时,我应该改变它实际上应该是用户控制器而不是商店控制器吗?
    • 那里没有实际的正确答案。如果它是用户最喜欢的商店,那么一个好的路径可能是 `GET|POST /users/:user_id/stores' 并且您可能想要创建一个特定的控制器(UserStoresController 或 User::StoresController)来处理它。但您可能想就该主题提出一个新问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-22
    相关资源
    最近更新 更多