1

内のネストされたモデルで目的の検証を取得するのに苦労していますsimple_form。以下のモデルからわかるように、 a にPersonは多くPhoneの があります。望ましい動作は、既存の数字の編集フィールドを表示することと、この新しい数字がユーザーの場合、それは単に無視され、データベースに保存されません。私も同様のことを達成したいと考えていEmailます。

/people/:id/edit ページに到達すると、この空白のフィールドは時期尚早に検証され、フォームを送信する前に目に見えるエラーが発生します。/people/:id/new ページにアクセスするときはこれを行いません。これはnew_record?、新しいページのユーザー モデルに対して true を返すためだと思いますか? 同様の投稿を読んで、モデルon: :saveにパラメーターとして追加しましたが、これはデータベースに空白のレコードを許可しただけですが、おそらくユーザーモデルがレコードを保存しているときにこれは関係ないからですか?validatesPhone

class Person < ActiveRecord::Base
  belongs_to :company
  has_many :phones, :as => :phoneable
  has_many :emails, :as => :emailable
  has_many :addresses, :as => :addressable
  attr_accessible :first_name, :job_title, :last_name, :prefix, :phones_attributes, :emails_attributes, :addresses_attributes, :company_id
  accepts_nested_attributes_for :phones, allow_destroy: true, reject_if: proc { |attributes| attributes['number'].blank? }
  accepts_nested_attributes_for :emails, allow_destroy: true, reject_if: proc { |attributes| attributes['email'].blank? }
  accepts_nested_attributes_for :addresses, allow_destroy: true, reject_if: :all_blank
  validates :first_name, :last_name, presence: true

  def to_s
    "#{first_name} #{last_name}"
  end
end


class Phone < ActiveRecord::Base
  belongs_to :phoneable, polymorphic: true
  attr_accessible :number, :phone_type
  validates :number, :phone_type, presence: true, on: :save  # as suggested in a similar post, just allows blank records into database.
  def to_s
    "#{phone_type}: #{number}"
  end
end

new コントローラーと edit コントローラーの両方を使用して、これらの各モデルの新しいインスタンスを作成し、フォームに表示されるようにします。cancanの一部として@person使用してコントローラーにロードされます。load_and_authorize_resource

def new
  @person.phones << Phone.new
  @person.emails << Email.new
end

フォームの部分ビューを次に示します。

<%= simple_form_for @person, :html => { :class => 'form-horizontal' } do |f| %>
  <fieldset id="<%= controller.action_name.capitalize %>_person">
    <legend><%= controller.action_name.capitalize %> Person</legend>

    <%= f.input :prefix %>
    <%= f.input :first_name %>
    <%= f.input :last_name %>
    <%= f.input :job_title %>
    <%= f.association :company, :prompt => "Select associated company..."  %>

    <%= f.simple_fields_for :phones do |phone| %>
      <%= phone.input :phone_type, :collection => %w(Work Home Mobile Fax Other), :default => "Work" %>
      <%= phone.input :number %>
    <% end %>

    <%= f.simple_fields_for :emails do |email| %>
      <%= email.input :email_type, :collection => %w(Work Home Other), :default => "Work" %>
      <%= email.input :email %>
    <% end %>

    <div class="form-actions">
      <%= f.submit nil, :class => 'btn btn-primary' %>
      <%= link_to t('.cancel', :default => t("helpers.links.cancel")),
                  people_path, :class => 'btn' %>
    </div>    
  </fieldset>
<% end %>

事前に助けてくれてありがとう:-)

4

0 に答える 0