0

I have my Model :

class Course < ActiveRecord::Base
      include ActiveUUID::UUID
       validates :location, :description, presence: true
end

and DB model :

class CreateCourses < ActiveRecord::Migration
  def change
    create_table :courses, :id => false do |t|
      t.uuid :id, :primary_key => true, :null => false
      t.datetime :date_start, :null => false
      t.float :price, :null => false
      t.datetime :date_end
      t.text :description
      t.text :location, :null => false
      t.uuid :mentor_uuid
      t.timestamps
    end
  end
end

and my method in controller which i cal via ajax :

  def create
     @course  = Course.new(params.require(:course).permit(:description, :location))
    if @course.save
     render json: @course, status: 200
    else
       render json: @course.errors.full_messages, status: 400
    end 
  end

and here is my ajax call :

var course = {"description" : "Timo", 'location' : 'hahahah'};
    $scope.test = function(){
        $http.post('api/courses.json', course).success( function (data) {
        }).success(function(data){
            console.log(data);
        }).error(function(data){

            console.log(data);
        });
  };

So this return me an error with : ["Date end can't be blank", "Date start can't be blank", "Price can't be blank"], but what if i want to change error message to my specific one? Also, on error it only returns errors, hwo do i make rails also return "old" model which faild so user dont have to hit face agains the wall and type all the text again from scratch?

Timsen
  • 4,066
  • 10
  • 59
  • 117

1 Answers1

1

Attribute Names

As per this answer & this one, the core problem you have is your attribute name is prepending the error message. The way to fix this is to some how remove the attribute name from the error message:

#config/locales/en.yml
en:
  errors:
    format: "%{message}"

The default is %{attribute} %{message}

--

We've done it this way before, although I don't think this works in Rails 4:

<%= @model.errors.full_messages.each do |attribute, message| %>
   <%= message %>
<% end %>
Community
  • 1
  • 1
Richard Peck
  • 76,116
  • 9
  • 93
  • 147