Rails - 递归用户模型关系的模型关联

时间:2013-09-27 02:38:48

标签: ruby-on-rails ruby-on-rails-4 rails-models

在我的用户模型中,我有

  belongs_to :admin_creator, foreign_key: :created_by_user_id, class_name: "User"

在我的创建控制器操作中我有......

def create
    @user = User.new(user_create_params)
    @user.created_by_user_id = current_user.id
    @user.status_code = 'P' #set status code to pending

    begin
      @user.save!
      render json: "User #{@user.email} added", status: :created 
    rescue StandardError => e
      render json: @user.errors.full_messages, status: :unprocessable_entity 
    end

  end

如何重新编写代码以使用“current_user”的模型关联作为admin_creator?

调用create action时,current_user是添加另一个(子)用户帐户的当前管理员用户。我认为这将是... @user = current_user.users.build(user_create_params)或类似的

1 个答案:

答案 0 :(得分:1)

has_many添加到User模型中,如下所示:

has_many :admin_children, foreign_key: :created_by_user_id, class_name: "User"

然后你可以这样做:

current_user.admin_children.create(user_create_params)