我需要验证是否已将信用分配到表单中的跟踪。该曲目正在保存,errors.add
无效。
想法?
class Track
has_many :credits
accepts_nested_attributes_for :credits, allow_destroy: true
attr_accessible :credits_attributes
has_many :vendors, through: :credits
accepts_nested_attributes_for :vendors
attr_accessible :vendor_ids
end
尝试验证表单的Credit位是否填写在Track编辑页面上:
def verify_credits
@track = Track.find(params[:id])
if !params.has_key?(:split) || params[:track][:credits_attributes][:vendor_id].empty?
puts '*' * 300
@track.errors.add(:base, 'You must credit this track to a Vendor with a split')
end
end
我在ActiveAdmin track.rb中覆盖的控制器操作中调用verify_credits
。放置' *'即将到来所以我知道我的条件很好。例如:
def update
referrer = params[:track][:referrer]
params[:track].delete(:referrer)
s3_path = params[:track][:file_cache] if params[:track][:file_cache]
params[:track].delete(:file_cache) unless s3_path.empty?
@track = Track.find(params[:id])
@track.assign_attributes(params[:exclusivities])
verify_credits
authorize! :update, @track
if s3_path
Delayed::Job.enqueue ProcessTrackFileJob.new(@track.id, s3_path) unless s3_path.empty?
end
super do |format|
format.html { redirect_to referrer } unless referrer.to_s.empty?
end
end
增加:
_form.html.erb
<%= f.inputs "Vendors" do %>
<% f.has_many :credits do |c|%>
<% c.input :vendor, as: :string, required: true, input_html: { %>
<% class: 'autocomplete', %>
<% name: '', %>
<% value: c.object.vendor.try(:name), %>
<% data: { %>
<% url: autocomplete_manage_vendors_path %>
<% } %>
<% } %>
<% c.input :vendor_id, as: :hidden %>
<% c.input :_destroy, as: :boolean, required: false, label: "Remove" %>
<% c.input :split %>
<% end %>
<% end %>
<% end %>
答案 0 :(得分:0)
您的Track
模型中没有任何验证。如果您要确保有vendor_id
,则validates :vendor_id, presence: true
模型中需要Track
。如果没有,则Track
型号不知道如果缺少vendor_id
则会出现错误。