1

別のモデルに属する属性の存在を検証しようとしましたが、役に立ちませんでした。

持っている

  • ユーザーモデル
  • プロファイルモデル

このフォームの使用:

= 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) + " »"

上記のフォーム設定で性別フィールドの存在を検証するにはどうすればよいですか?

4

2 に答える 2

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

于 2012-06-15T13:48:41.877 に答える
-1

上記は正解であり、そのように実装しましたが、性別フィールドはまったく検証されていないようです。まだ同じ問題のようなものです。質問を再開することは可能ですか?

于 2012-06-17T10:48:57.263 に答える