【问题标题】:validate presence of fields from another model验证来自另一个模型的字段是否存在
【发布时间】:2012-06-14 11:13:53
【问题描述】:

我尝试验证是否存在属于另一个模型的属性,但无济于事。

拥有

  • 用户模型
  • 个人资料模型

使用这种形式:

= simple_form_for(resource, :as => resource_name, :html => { :class => 'form-horizontal' }   , :validate => true , :url => registration_path(resource_name)) do |f|

= f.input :username,                  :label  => t(:username)
= f.input :email,                     :label  => t(:email),
                                      :hint   => t(:hint_email_visible)
= f.input :password,                  :label  => t(:password), :require => true
= f.input :password_confirmation,     :label  => t(:password_confirm)

- resource.build_profile
= f.fields_for :profile do |f|

 #render
   = f.hidden_field :form, :value => "signup"

    .clear
    = f.input :gender,
              :label => t(:your_gender),
              :collection => gender,
              :item_wrapper_class => 'inline',
              :as => :radio_buttons


.clear
= f.button :submit, t(:submit, :scope => :register) + " »"

如何使用上述表单设置验证性别字段的存在?

【问题讨论】:

  • 嗨,为什么不在代码中使用accepts_nested_attributes_for?
  • 能否详细说明这一点,并提供一个简短的例子来说明这应该如何提供帮助?
  • 谢谢,这正是我所需要的,谢谢,如果您将其发布为回复而不是评论,我可以为您提供正确的答案。

标签: ruby-on-rails-3 validation activerecord model


【解决方案1】:

下面的代码可以帮助你。

控制器/users_controller.rb

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

models/users.rb

class User < ActiveRecord::Base
  has_one :profile, dependent: :destroy
  accepts_nested_attributes_for :profile, :allow_destroy => true
end

models/profile.rb

class Profile < ActiveRecord::Base
   validates_presence_of :gender
end

您可能需要从视图中删除以下行。

- resource.build_profile

这是您认为有用的链接

http://railscasts.com/episodes/196-nested-model-form-part-1

【讨论】:

    【解决方案2】:

    虽然上面是正确的答案并且我已经实现了它,但性别字段似乎仍然没有得到验证。所以有点还是在同一个问题上。是否可以重新打开问题?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-23
      • 2015-09-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-28
      相关资源
      最近更新 更多