msdundar
msdundar

Reputation: 383

Rails - Validation Error Messages is not Appearing

I'm having problems with validation error messages in my Rails4 application. They don't show up somehow. When they triggered, only the "Please review the problems below" message is appearing and nothing more, no error messages.

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 =>

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 =>

<%= 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 %>

What is wrong with my code?

Thanks in advance.

Upvotes: 0

Views: 2181

Answers (3)

Arpit Vaishnav
Arpit Vaishnav

Reputation: 4780

Please have a look at the example

class Invoice < ActiveRecord::Base
  validate :active_customer, on: :create
 
  def active_customer
    errors.add(:customer_id, "is not active") unless customer.active?
  end
end

Check this link for more details

Upvotes: 0

Arihant Godha
Arihant Godha

Reputation: 2469

You can try this. This will generate one error at a time

<% 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 %>

Upvotes: 1

neo-code
neo-code

Reputation: 1076

Try this>>>

 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

Upvotes: 1

Related Questions