【问题标题】:How to create new User with an Organization association如何使用组织关联创建新用户
【发布时间】:2014-08-25 21:10:38
【问题描述】:

在我的 web 应用程序中,我的用户注册页面有一个组织名称字段。我有一个 has_many :users 的组织模型和我的用户模型 belongs_to :organization。创建新用户时,我希望使用组织名称值来创建新组织记录,并将其与用户相关联,这样 user.organization_id = 新组织 ID。

这是我的 users_controller.rb 代码:

class UsersController < ApplicationController
  def new
    @user = User.new
  end

  def show
    @user = User.find(params[:id])
    @organization = Organization.find(@user.organization_id)
  end

  def create
    @organization = Organization.new(organization_params)
    @user = User.new(user_params)
    if @user.save && @organization.save
      sign_in @user
      redirect_to @user
      flash[:success] = "Welcome to the App!"
    else
      flash.now[:danger] = "Uh oh, there's been an error"
      render 'new'
    end
  end



  private
    def user_params
      params.require(:user).permit(:name, :email, :password,
                                   :password_confirmation)
    end

    def organization_params
      params.require(:organization).permit(:name)
    end
end

目前,当用户提交注册表单时,正在创建用户记录和组织记录,但未保存关联。 user.organization_id 的值为 nil。

您能否评论一下出了什么问题,以及是否有一种好方法可以做我想做的事情——也许使用 .build?

谢谢! 布伦南

【问题讨论】:

    标签: ruby-on-rails forms ruby-on-rails-4 associations


    【解决方案1】:

    是的! .build 可以工作,但是因为它是一个单一的关联,您将在构建命令中使用关联名称,即build_organization

    def create
      @user = User.new(user_params)
      @user.build_organization(organization_params)
      if @user.save
        blah blah blah
    

    如果这样做,您只需要保存用户(而不是@organization),因为关联已被处理。

    【讨论】:

    • 感谢 JTG!我现在就试试。
    • 这就像一个魅力,JTG - 非常感谢!我已经为此苦苦挣扎了好几天;-)
    • 有没有一种好方法可以用这种方法来验证是否存在组织关联?现在你可以创建一个没有组织的用户,它仍然可以通过。
    • @bnzelener 将validates :organization, presence: true 放入您的app/models/user.rb。如果您还有其他问题,请随时提出一个新的 SO 问题(当然,在研究之后,如果您仍然被卡住;))。并随时接受此作为答案,以帮助以后可能有相同问题的其他人。
    【解决方案2】:

    在 user_params 允许 :organization_id ;)

    def user_params
      params.require(:user).permit(:name, :email, :password, :password_confirmation, :organization_id)
    end
    

    编辑:您还需要在某处为用户设置 organization_id - 如果您没有在表单中执行此操作(例如使用 select 或其他字段),您可以使用 .build 方法。

    【讨论】:

      猜你喜欢
      • 2016-11-19
      • 2013-02-17
      • 1970-01-01
      • 1970-01-01
      • 2018-08-28
      • 1970-01-01
      • 2015-02-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多