关联模型和带有验证的嵌套表单不起作用

Nic*_*ick 1 ruby validation ruby-on-rails nested-forms ruby-on-rails-4

Update2:我已经清理了代码,这似乎解决了一些问题。我已将新代码作为新问题发布在此处

更新:组织和用户有一对多的关系。我的问题涉及需要组织和用户的联合注册表单。在 maxcal 对原帖的帮助之后,我create为我的嵌套表单(“组织有很多用户”)编写了一个新方法,如下所示。我也添加begin...rescue...endcreate方法中。现在的情况/问题:

  • 提交所有有效信息,它可以正常工作。
  • 提交了组织的无效信息(用户是否也无效都没有关系),它会按照我们的意愿呈现带有错误消息的页面,但它只显示组织详细信息的错误。此外,对于用户详细信息,它已清空了所有不应清空的字段。
  • 仅针对用户提交无效信息,它再次呈现表单,但没有任何错误消息,并且用户的所有字段都已清空。

有人知道代码有什么问题吗?问题似乎更多是嵌套用户而不是组织(父)。此外,users_attributes.empty?不起作用,因为根据日志,空提交的表单仍然包含此类属性:

Parameters: {"utf8"=>"?", "authenticity_token"=>"***", "organization"=>{"name"=>"", "bag"=>"", "users_attributes"=>{"0"=>{"email"=>"", "username"=>"", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]", "usertype"=>"2", "admin"=>"true"}}}, "commit"=>"Register"}
Run Code Online (Sandbox Code Playgroud)

.

  def create
    @organization = Organization.new(new_params.except(:users_attributes))
begin
    if users_attributes.empty?
        @organisation.errors.add(:users, 'No user provided')
    end
    @organization.transaction do
      @organization.save!
      if users_attributes.any?
        @organization.users.create!(users_attributes)
      end
    end
rescue ActiveRecord::RecordInvalid => invalid
    if @organization.persisted?
      if @organization.users.any?
        @organization.users.each do |single_user|
          single_user.send_activation_email
        end
      end
      flash[:success] = "Confirmation email sent."
      redirect_to root_url
    else
      @organization.users.build if @organization.users.blank? 
      render :new
    end
end
  end

private
  # converts the hash of nested attributes hashes to an array
  def users_attributes
     new_params[:users_attributes].values
  end
end
Run Code Online (Sandbox Code Playgroud)

原始问题: 我有两个关联模型和一个带验证的嵌套表单。不幸的是,它不起作用。1)在播种时会产生错误Validation failed: Users organization can't be blank。我之前发布了一个关于这个的问题,并过早地得出结论它已经解决了它。它没有。2) 提交我的嵌套注册表并正确填写所有字段,会产生 flash 错误消息The form contains 1 error. Users organization can't be blank

我应该如何调整我的代码来解决这些问题?

模型文件:

#User model
belongs_to :organization, inverse_of: :users
validates_presence_of :organization_id, :unless => 'usertype == 1'

# Organization model
has_many :users, dependent: :destroy
accepts_nested_attributes_for :users, :reject_if => :all_blank, :allow_destroy => true

validate  :check_user
private
  def check_user
    if users.empty?
      errors.add(:base, 'User not present')
    end
  end
Run Code Online (Sandbox Code Playgroud)

组织控制器方法

  def new
    @organization = Organization.new
    @user = @organization.users.build
  end

  def create
    @organization = Organization.new(new_params)
    if @organization.save
      @organization.users.each do |single_user|
        single_user.send_activation_email                 # Method in user model file.
      end
      flash[:success] = "Confirmation email sent."
      redirect_to root_url
    else
      @organization.users.build if @organization.users.blank?
      render 'new'
    end
  end

def new_params
  params.require(:organization).permit(:name, :bag,
             users_attributes: [:email, :username, :usertype, :password, :password_confirmation])
end
Run Code Online (Sandbox Code Playgroud)

表格:

  <%= form_for @organization, url: organizations_path do |f| %>
    <%= render 'shared/error_messages', object: f.object %>
    <%= f.text_field :name %>
    <%= f.text_field :bag %>
    <%= f.fields_for :users do |p| %>
      <%= p.email_field :email %>
      <%= p.text_field :username %>
      <%= p.text_field :fullname %>
      <%= p.password_field :password %>
      <%= p.password_field :password_confirmation %>
      <%= p.hidden_field :usertype, value: 2 %>
    <% end %>
Run Code Online (Sandbox Code Playgroud)

在我的种子文件中,我有:

Organization.create!(name: "Fictious business",
                     address: Faker::Address.street_address,
                     city: Faker::Address.city,
  users_attributes: [email: "helpst@example.com",
                     username: "helpyzghtst", 
                     usertype: 2,
                     password: "foobar", 
                     password_confirmation: "foobar"])
Run Code Online (Sandbox Code Playgroud)

提交注册表时的错误日志:

Started POST "/organizations" 
Processing by OrganizationsController#create as HTML
  Parameters: {"utf8"=>"?", "authenticity_token"=>"0cR***Nnx4iReMiePg==", "organization"=>{"name"=>"test21", "bag"=>"tes21", "users_attributes"=>{"0"=>{"email"=>"test21@example.com", "username"=>"test21", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]", "usertype"=>"2"}}}, "commit"=>"Register"}
   (0.2ms)  BEGIN
  User Exists (1.1ms)  SELECT  1 AS one FROM "users" WHERE LOWER("users"."email") = LOWER('test21@example.com') LIMIT 1
   (0.7ms)  SELECT "users"."email" FROM "users"  ORDER BY "users"."username" ASC
  User Exists (0.3ms)  SELECT  1 AS one FROM "users" WHERE LOWER(users"."username") = LOWER('test21') LIMIT 1
  Organization Exists (0.6ms)  SELECT  1 AS one FROM "organizations" WHERE LOWER("organizations"."name") = LOWER('test21') LIMIT 1
  Organization Exists (0.4ms)  SELECT  1 AS one FROM "organizations" WHERE LOWER("organizations"."bag") = LOWER('tes21') LIMIT 1
   (0.2ms)  ROLLBACK
Run Code Online (Sandbox Code Playgroud)

max*_*max 5

由于Catch-22,您的验证不起作用

要申请这份工作,你必须疯了;但如果你疯了,你是不可接受的。

ActiveRecord 模型在保存时从数据库中获取它们的 ID。但是对嵌套用户的验证在组织插入数据库之前运行。

你会猜想,只是检查validates_presence_of会通过:

validates_presence_of :organization, unless: -> { usertype == 1 }
Run Code Online (Sandbox Code Playgroud)

不幸的是没有。为了validates_presence_of :organization传递,必须将组织持久化到数据库中。再次抓住22。

为了通过验证,我们需要将创建组织和用户分为两个步骤:

org = Organization.create(name: 'M & M Enterprises')
user = org.users.build(username: 'milo_minderbinder', ...)
user.valid? 
Run Code Online (Sandbox Code Playgroud)

不幸的是,你不能使用的手段accepts_nested_attributes_for :users- 至少不是直接的。

通过使用事务,我们可以将组织插入数据库,并在用户无效时回滚。

def create
  @organization = Organization.new(new_params.except(:users_attributes))
  @organization.transaction do
    @organization.save!
    if new_params[:users_attributes].any?
      @organization.users.create!(new_params[:users_attributes])
    end
  end
  if @organization.persisted?
    # ...
    if @organization.users.any?
      # send emails ... 
    end
  else
    @organization.users.build if @organization.users.blank? 
    render :new
  end
end
Run Code Online (Sandbox Code Playgroud)

后续问题

我们使用是@organization.persisted?因为无论是否创建了用户记录,我们大概都想重定向到新创建的组织。

因为电子邮件是发送给用户的?这应该无关紧要,因为如果没有创建用户,组织就会回滚。

如果没有创建用户,则事务不会回滚。仅当用户因参数无效而无法保存时。这是基于您的要求:

但是组织也可以(暂时)没有用户。

如果您需要 @organisation 在没有用户的情况下无效,您可以执行以下操作:

  @organisation.errors.add(:users, 'No users provided') unless new_params[:users_attributes].any?
  @organization.transaction do
    @organization.save!
    if new_params[:users_attributes].any?
      @organization.users.create!(new_params[:users_attributes])
    end
  end
Run Code Online (Sandbox Code Playgroud)

您将@organization.users.any?用来检查是否有任何用户。@organization.users.persisted?将不起作用,因为它.persisted?是模型实例上的一种方法 - 而不是集合。

另一方面,我认为使用这种方法(不应该)覆盖/更新现有组织/用户而不是总是创建新记录是不可能的?

是的,由于这将始终发出两个 SQL 插入语句,因此不会更改现有记录。

然而,由您来创建保证数据库列唯一性的验证(即,您不希望多个记录具有相同的 user.email 或organiation.name)。

好的一面是,在更新现有组织时,这些警告都不适用:

def update
  @organisation.update(... params for org and and users ...)
end
Run Code Online (Sandbox Code Playgroud)

因为在验证用户时您不会遇到整个鸡或蛋的困境。