【问题标题】:form validation with nested models in Rails在 Rails 中使用嵌套模型进行表单验证
【发布时间】:2016-04-29 08:27:30
【问题描述】:

我有这个问题。我需要在 Rails 中以相同的形式验证两个模型的属性。一个是另一个的父级。

表格是这样的:

<%= semantic_form_for @professional do |pro| %>
       <%= pro.inputs :id => "information" do %>
          <%= pro.input :name, label: t("Artistic Name") %>
         <%= pro.semantic_fields_for @user do |user| %>

         <%= user.inputs :id => "register" do %>

            <%= user.input :email, :placeholder=>"email@example.com" %>

           <%= user.input :password, label: t('Password') %>

          <%end%>

       <% end %>

   <% end %>

<% end %>

我使用的模型是这样的:

用户:

class User < ActiveRecord::Base
  belongs_to :role, polymorphic: true
  validates  :email, :password, presence: true

end

专业人士:

class Professional < ActiveRecord::Base
 has_one :user, as: :role, dependent: :destroy

 accepts_nested_attributes_for :user

   validates  :date_birthday, :gender, :height, :name, :description, :Weight, :address, :languages,:services, :category, :phonenumber, :fullname, :hair_color, :age, :orientation, presence: true

end

那么,问题出在哪里?

当我单击提交按钮时,会标记专业属性,但不会标记用户属性。

像这样:

标记为红色的字段属于专业模型,但属于用户模型的字段电子邮件和密码未标记为红色,因为它们是空的。

我能做什么?我也需要用户的警告信息是属性

提前致谢。

【问题讨论】:

  • 您的关联设置是否正确?
  • @RichPeck 我用两个模型之间的关联编辑了模型代码

标签: ruby-on-rails forms validation


【解决方案1】:

我们之前已经实现了您所需要的。

我们必须使用inverse_of,以便对象是单个数据片段(而不是默认情况下的多个片段):

#app/models/user.rb
class User < ActiveRecord::Base
  belongs_to :role, polymorphic: true, inverse_of: :user
  validates  :email, :password, presence: true
end

#app/models/professional.rb
class Professional < ActiveRecord::Base
  has_one :user, as: :role, dependent: :destroy, inverse_of: :role
  accepts_nested_attributes_for :user
end

This 会有所帮助。

您还需要确保正确传递这些对象(我看到很多人没有这样做)。

【讨论】:

    【解决方案2】:

    您需要告诉 Professional 验证关联的用户:

    class Professional < ActiveRecord::Base
        ... 
        validates_associated :user
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-29
      • 2015-12-28
      • 1970-01-01
      • 2011-10-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多