简体   繁体   English

关联belongs_to vs嵌套形式的属性

[英]Association belongs_to vs nested attributes in the form

I have a situation like below: 我有如下情况:

class User < ActiveRecord::Base
  belongs_to :user_group
  accepts_nested_attributes_for :user_group
end

class UserGroup < ActiveRecord::Base
  has_many :users
end

Controller: 控制器:

UsersController < ApplicationControler
  def new
    @user = User.new
    @user.build_user_group
  end

  def create
    @user = User.new(user_params)

    if @user.save
      # do something
    else
      # do something
    end
  end

  private

  def user_params
    params.require(:user).permit(:email, :username, user_group_attributes: [:name])
  end
end

Form: 形成:

= simple_form_for @user do |f|
            = f.input :username
            = f.simple_fields_for :user_group do |builder|
              = builder.input :name, collection: UserGroup.all.map(&:name), prompt: "Choose one"
            = f.input :email
            = f.button :submit, 'Create', class: 'btn btn-success'

But it doesn't create an user with the association between the user and the user_group. 但是,它不会通过用户与user_group之间的关联来创建用户。 UserGroup table is just a list of user groups, eg moderator, user and so on. UserGroup表只是用户组的列表,例如主持人,用户等。 So I need to select a group in the form and create a new user with association. 因此,我需要在表单中选择一个组并创建一个具有关联的新用户。 What am I doing wrong? 我究竟做错了什么? Do I need to find a group in create action and pass it as @user.user_group = the_chosen_group ? 我是否需要在create操作中找到一个组并将其作为@user.user_group = the_chosen_group

PS Is it a proper name convention of UserGroup? PS是UserGroup的正确名称约定吗? Maybe should I call it as Group? 也许我应该将其称为“组”?

Regards. 问候。

Nested attributes should only be used when you want to allow editing of associated object via object itself. 仅当您希望允许通过对象本身编辑关联对象时,才应使用嵌套属性。 In short, every time you submit the form you created, rails will receive params like: 简而言之,每次您提交创建的表单时,rails都会收到以下参数:

{ username: 'sth', user_group_attributes: { name: 'Group name' }

When you assign attributes like this, rails will create new attribute group, as it has no idea it is to search for such a group. 当您分配这样的属性时,rails将创建新的属性组,因为它不知道要搜索这样的组。

Since you only want to assign given user to usergrooup, you do not need nested_attributes at all. 由于您只想将给定用户分配给usergrooup,因此根本不需要nested_attributes。 All you need is: 所有你需要的是:

= simple_form_for @user do |f|
  = f.input :username
  = f.input :user_group_id, collection: UserGroup.all.pluck(:name, :id), prompt: 'Choose one'
  = f.input :email
  = f.button :submit, 'Create', class: 'btn btn-success'

And in the controller: 并在控制器中:

def user_params
  params.require(:user).permit(:email, :username, :user_group_id)
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM