我的Rails4应用程序中的验证错误消息出现问题。他们不会以某种方式出现。当它们被触发时,只显示“请查看下面的问题”消息,仅此消息,没有错误消息。
order.rb =>
Class Order < ActiveRecord::Base
....
attr_accessor :card_number, :card_verification
validate :validate_card, :on => :create
private
def validate_card
unless credit_card.valid?
credit_card.errors.full_messages.each do |message|
errors.add(:base, message)
end
end
end
end
orders_controller.rb =&gt;
def create
@order = Order.new(order_params)
@order.ip_address = request.remote_ip
@order.user_id = current_user.id
respond_to do |format|
if @order.save
if @order.purchase
format.html { render action: "success", notice: 'Perfect!' }
else
format.html { render action: "failure" }
end
else
format.html { render action: 'new' }
end
end
end
/orders/new.html.rb =&gt;
<%= simple_form_for(@order, html:{class: "well"}, :method => :post) do |f| %>
<%= f.error_notification %>
<%= f.input :participation_id, collection: Participation.where(user_id: current_user.id), as: :select, label_method: lambda{|x| x.examination.name}, label: 'Choose' %>
<%= f.input :first_name, label: 'Name' %>
<%= f.input :last_name, label: 'Surname' %>
.........
<%= f.button :submit %>
<% end %>
我的代码出了什么问题?
提前致谢。
答案 0 :(得分:1)
试试这个&gt;&gt;&gt;
Class Order < ActiveRecord::Base
....
attr_accessor :card_number, :card_verification
validate :validate_card, :on => :create
private
def validate_card
unless credit_card.valid?
errors.add(:credit_card, "your message")
end
end
end
答案 1 :(得分:1)
你可以试试这个。这将一次产生一个错误
<% if @order.errors.full_messages.any? %>
<% @order.errors.full_messages.each do |error_message| %>
<%= error_message if @order.errors.full_messages.first == error_message %> <br />
<% end %>
<% end %>
答案 2 :(得分:0)
请看一下示例
class Invoice < ActiveRecord::Base
validate :active_customer, on: :create
def active_customer
errors.add(:customer_id, "is not active") unless customer.active?
end
end
查看此link了解详情