Railsfields_for复选框以创建新记录

时间:2018-12-05 22:55:17

标签: ruby-on-rails forms

我目前正在处理一个表单来编辑用户的信息,表单的一部分是检查其所扮演的角色。

角色存储在自己的表中,该表具有角色类型和用户的ID。

我要做的是选中这三种角色的复选框,用户可以检查他们应该拥有的角色。

基本上,表单应如下所示:

enter image description here

问题是我不知道如何使用表单构建器进行设置。我为用户设置了accepts_nested_attributes_for :roles,但不确定fields_for的工作方式。

有什么想法吗?

2 个答案:

答案 0 :(得分:0)

您不需要嵌套属性即可简单地将关联分配给记录。

首先,您要更改表和关联以创建规范化表:

class User < ApplicationRecord
  has_many :user_roles, dependent: :destroy
  has_many :roles, through: :user_roles
end

# remove user_id from the roles table
class Role < ApplicationRecord
  validates_uniqueness_of :name
  has_many :user_roles, dependent: :destroy
  has_many :users, through: :user_roles
end

# rails g model user_role user:references role:references
class UserRole < ApplicationRecord
  validates_uniqueness_of :role_id, scope: :user_id
  belongs_to :user
  belongs_to :role
end

这意味着角色的定义nameroles表中仅定义一次,而不是为应用于用户的每个角色重复。要将角色分配给用户,您只需在连接表中添加一个角色ID和用户ID,即可更有效地对其进行索引。

由于我们不需要为每个用户角色设置重复的名称列,因此我们可以使用role_ids=来设置复选框的用户角色。

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

class UsersController < ApplicationController

  # ...

  def create
    @user = User.new(user_params)
    # ...
  end

  # ...

  private
    def user_params
      params.require(:user)
            .permit(:foo, :bar, role_ids: [])
    end
end

答案 1 :(得分:-1)

https://guides.rubyonrails.org/form_helpers.html#nested-forms

给出的示例是:

<%= form_for @person do |f| %>
  Addresses:
  <ul>
    <%= f.fields_for :addresses do |addresses_form| %>
      <li>
        <%= addresses_form.label :kind %>
        <%= addresses_form.text_field :kind %>

        <%= addresses_form.label :street %>
        <%= addresses_form.text_field :street %>
        ...
      </li>
    <% end %>
  </ul>
<% end %>

要适应这一点,我假设您已经设置了模型:

<%= form_for @user do |f| %>
  <%= f.input :first_name %>
  <%= f.input :last_name %>
  Role:
  <ul>
    <%= f.fields_for :roles do |role_f| %>
      <li>
        <%= role_f.check_box :it %>
        <%= role_f.check_box :accounting %>
        <%= role_f.check_box :sales%>
      </li>
    <% end %>
  </ul>
<% end %>

从那里您可以看到参数如何通过并根据需要创建角色

相关问题