Reputation: 89
So I've been creating a Rails API (A school project) and everything works fine, but now I want to add some restrictions to the POST endpoint. So here is my create endpoint when I'm going to foo.com/api/v1/slogans :
def create
slogan = Slogan.new(slogan_params)
if(slogan.save)
render json: {
status: 'SUCCESS',
message: 'Saved slogan',
data: slogan
}, status: :ok
else
render json: {
status: 'ERROR',
message: 'Slogan not saved',
data: slogan.error
}, status: :unprocessable_entity
end
end
And these are my slogan_params :
private def slogan_params
params.permit(:firstname, :lastname, :email, :slogan)
end
Now how do I add restrictions to this, for example a character limit? I've already added one on my front end but I want to be sure that even if the front end is manipulated that the data don't get submitted if valid.
I thought about adding something in def create
but not sure if that is the way to do it.
Upvotes: 0
Views: 59
Reputation: 518
You can use
class Slogan < ActiveRecord::Base
validates :email, presence: true
end
And in controller you can do
def create
slogan = Slogan.new(slogan_params)
if slogan.valid?
slogan.save
render json: {
status: 'SUCCESS',
message: 'Saved slogan',
data: slogan
}, status: :ok
else
render json: {
status: 'ERROR',
message: 'Slogan not saved',
data: slogan.errors
}, status: :unprocessable_entity
end
end
Upvotes: 0