Rails has_one,belongs_to,join_table和嵌套表单

问题描述 投票:0回答:1

我正在创建用户,角色和用户角色。用户可以创建角色列表,并且在新用户表单中,有一个嵌套表单,其中填充了创建的角色列表,然后用户可以选择角色并与新用户相关联。我能够创建角色列表,但是在新的用户视图文件中创建嵌套表单时遇到问题。

这里是模型,如果关系正确,请告诉我。

class User < ApplicationRecord
  has_one :user_role
  has_one :role, through: :user_role
end

class Role < ApplicationRecord
  has_many :user_roles
  has_many :users, through: :user_roles
end

class UserRole < ApplicationRecord
  belongs_to :user
  belongs_to :role
end

User控制器。我不确定我的控制器是否正确:

def new
  @user = User.find_by_id(params[:id])
  @user = @current_user.account.users.new
  @user.build_user_role
end

def create
  @user = User.find_by_id(params[:id])                
  @user = @current_user.account.users.create_with_password(user_params)
    if @user.save
       redirect_to users_path
    else
       render 'new'
    end
end

private
def user_params
  params.require(:user).permit(:id, :email, :password, :password_confirmation, :admin, :owner, user_role_attributes: [:user_id, :role_id])
end

end

下面是新用户表格:

<%= form_for(@user, remote: true) do |f| %>

<%= f.text_field :email, class: "form-control", autofocus: true, autocomplete: "off" %>
<%= f.check_box :admin, class:"checkbox" %>
<%= f.check_box :owner, class:"checkbox" %>

<%= f.fields_for :user_role do |ff| %>
<%= ff.collection_select :role_id, @roles, :id, :role_name, include_blank: false %>
<% end %>             

<%= f.button "Create",  class: "btn btn-success" %>

<% end %>

user_role的嵌套形式没有显示,还请告知UserRoleUserRole之间的关系是否正确。

ruby-on-rails activerecord nested-forms has-one-through
1个回答
0
投票

如果用户只能拥有一个角色,那么您实际上根本不需要user_roles联接表:

class User < ApplicationRecord
  belongs_to :role
end

class Role < ApplicationRecord
  has_many :users
end

尽管假设您实际上并不需要多对多的关联似乎很天真,但实际上这要有用得多。例如:

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

class Role < ApplicationRecord
  has_many :users
  has_many :roles, through: :user_roles
end

class UserRole < ApplicationRecord
  belongs_to :user
  belongs_to :role
end

您还将进入一个普通的初学者陷阱,在其中您只需选择一个关联就可以将嵌套属性混淆。

您不需要@user.build_user_rolef.fields_for :user_role。您只需要选择一个并将role_id参数列入白名单:

<%= form_for(@user, remote: true) do |f| %>
  # ...
  <%= f.collection_select :role_id, @roles, :id, :role_name, include_blank: false %>
  # ...
<% end %>

def new
  # why even do this if you are just reassigning it on the next line?
  @user = User.find_by_id(params[:id]) 
  @user = @current_user.account.users.new
end

def create
  @user = User.find_by_id(params[:id])
  # Violation of Law of Demeter - refactor!
  @user = @current_user.account.users.create_with_password(user_params)
  if @user.save
    redirect_to users_path
  else
    render 'new'
  end
end

private
def user_params
  params.require(:user)
        .permit(
          :id, :email, :password, 
          :password_confirmation, 
          :admin, :owner, 
          :role_id # this is all you really need
        )
end
© www.soinside.com 2019 - 2024. All rights reserved.