'Creative'モデルの'size'プロパティの検証を追加しようとしています。「クリエイティブ」モデルは「広告」に1対1で関連付けられており、そのフィールドは「広告」フォーム(以下に提供されるコード)にネストされたフォームとして表示されます。
問題は、実際にフォームを保存しているときに、サイズが検証されないことです。フォーマットバリデーターでも、:presenceバリデーター(追加した場合)でもありません。同時に、:filterプロパティが検証されます。
サイズは非モデルプロパティであり、attr_acessorメソッドとカスタムセッターおよびゲッターが追加されています。
このコードを修正する方法、またはモデル以外のネストされたプロパティの検証を追加するための別のソリューションを探すことは非常にありがたいことです。
コントローラー:
class Creative < ActiveRecord::Base
attr_accessible :size, :filter
belongs_to :ad
attr_accessor :size
validates :size, :format => { :with => /^\d+x\d+$/, :message => "Incorrect size param. Should be [width]x[height], e.g. 320x50" }
validates :filters, :presence => true
def size
"#{self.width}x#{self.height}"
end
def size=(size)
@width, @height = size.split("x").map(&:to_i)
end
end
class Ad < ActiveRecord::Base
attr_accessible :creative_attributes
has_one :creative
accepts_nested_attributes_for :creative
validates_associated :creative
end
class Campaign < ActiveRecord::Base
has_many :ads
end
形:
<%= simple_form_for [:rtb, @campaign, @ad], :html => { :class => 'form-horizontal' } do |f| %>
<% if @ad.errors.any? %>
<div id="error_explanation" class="alert alert-error">
<h2><%= pluralize(@ad.errors.count, "error") %> prohibited this ad from being saved:</h2>
<ul>
<% @ad.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<%= f.input :name %>
<%= f.simple_fields_for :creative do |creative_f| %>
<fieldset>
<legend>Creative Settings</legend>
<%= creative_f.input :size %>
<%= creative_f.input :filters %>
</fieldset>
<% end %>
<%= f.button :submit, :class => 'btn-primary' %>
<% end %>