Rails validation required parameter (lock_version) - ruby-on-rails

I have a question about how can I validate a required change at rails model.
for example:
to the param lock_version we need the validate if this value always is present when tried to update the model.
has rails some validation to test the change presence?
Thanks

This type of validation is handled by validates_presence_of.
Seems like you're looking for
validates_presence_of :lock_version, on: :update
I strongly advise to take a look on http://apidock.com/rails/ActiveRecord/Validations/ClassMethods/validates_presence_of
There are plenty of validations in Rails and this is probably the most basic one.
http://guides.rubyonrails.org/active_record_validations.html

#jakub is right, however if you want another way of validating fields you can use html validations. Add required: true to any field you need to be filled out. I.e
<%= f.text_field :lock_version, required: true %>
If a user tries to submit the form without this field they will get a flash message pop up over the field telling them to fill it out.
Justin

Related

Rails custom model validator depending on check_box value

Lets say i have a model "Blog" with :title and :body.
Lets also say that in my view I have input for title, body and a check_box_tag that looks like this
<%= check_box_tag "published" %>
Now, I want to write a custom validation for the :body that should run only if my checkbox "published" is checked.
The question is - how do i get the value of the ckeckbox since :published is not a model attribute?
You can't. Neither should you.
Validations ensure the buisness logic in the context of a instance of a model. Not a request. If you want to provide any other context to a validation you have to pass it into the model - and that data has to be saved somewhere until the validation callback is performed - in an attribute. This does not necissarily mean that it has to be a database column.
If you do want to get an parameter in the controller they can be found in the parameters hash according to the name attribute of the input.
params[:published]

How to validate presence of drop down list in Rails

I want to know how to validate that a user selected a value.
My collection_select is:
= f.collection_select :person_id, #employee, :id, :fullName, {prompt: "Select employee"}, {class: "form-control"}
I would use:
validates :person, :presence => true
This ensures that the selected person_id was not only present, but it also belongs to an existing Person.
Please note that if there are errors the errors will be added on :person, not on person_id. Depending on how you render validation errors you will have to check for error like this: object.errors[:person].
When you want to present errors next to the person_id field, but cannot update your view, then you might want to use a custom validation that checks person, but adds errors to person_id:
validate :person_existing
private
def person_existing
errors.add(:person_id, :missing) if person.blank?
end
For view tests in general, I would write a test against the returned HTML from the controller action. This gives the benefit of not doing in-browser tests (i.e. you don't have to use a web driver/headless browser), and since it's up to the individual browsers to render your HTML properly you can keep you tests simpler by just ensuring that the returned HTML from the controller action is correct.
If you want to validate that, when the user selects a given item, that it has been selected...well that's really up to the browser to do that job, so I don't know if you really want to test that. However, you should be able to check for the selected attribute on the tag (see here)
That said, in general don't go too crazy with view tests, if this is indeed what you're going for. The view is the part of most apps that changes very frequently, and is quite fragile. You may find yourself chasing view changes a lot in your test suite.

Validate Uniqueness and Edit Form in Rails

I have a form.
Same form is used for creating and editing...
In my model
validate_uniqueness_of :empID
is present..
and in my form on updating, I get the error that empID is already taken..
Is there any way i can exclude this validation in editing..
You can simply define that your validation should only come into effect on create
validates :empID, uniqueness: true, on: :create
"#TheChamp thing is in my edit form i have disabled the option to edit the id.. Since i want the id to be shown as disbaled in that page i cant remove those line for empID with a condition like if params[:action]==edit.. so hope this is the only solution.."
if all you want is for the empID not to be editable when the form is for an existing one... you can indeed check if the form is for editing and just display it like this:
(Assuming that the moel is in a variable called my_model)
# new_record? will only be true for a model that is being created, not edited
<% if my_model.new_record? %>
<%= f.select :empID, options_go_here %>
<% else %>
# don't display the field-here, instead just display the employee-info
<%= my_model.emp.name %>
<% end %>
Your application is doing exactly what you are instructing it to do.
You validate the uniqueness of the empID attribute which is on conflict upon the update request. Instead of only passing the validation upon it's create action you should think your logic through:
Is there any situation where multiple entries hold the same empID?
Why should the empID be unique? is it a primary key?
From my point of view it looks like empID defines a relation between the record and an emp model? if so adjust the validation to make it functional:
class Model < ActiveRecord::Base
belongs_to :emp
validates_presence_of :empID
end

validating checkbox acceptance for a form that doesn't have a model

I would like to add a validator to a checkbox, so that if it is not accepted the form will not be sent. Ideally it would be a Rails solution.
The form is emailed directly to the admin as opposed to being stored in the db, so, in my limited rails wisdom I would assume model validations will not work.
Here is the part of the form concerned with the validation.
<%= f.check_box :agree, {}, 'Agree', "Don't Agree" %>
EDIT
I had tried adding
validates :agree, acceptance: true
but with this is my model, wether accepted or not, the form keeps failing
Thanks in Advance
Rico

Rails: update_attributes not updating all attributes

I have a simple model called Discussion which has a boolean column called resolved.
In my form, I have the following code
<%= form_for(#discussion) do |d| %>
...
<%= d.check_box :resolved %>
<% end %>
And in my controller, I have the following:
def update
#discussion = Discussion.find(params[:id])
if #discussion.update_attributes(params[:discussion])
etc...
end
end
When I submit the form, I can see that the parameters are being sent to the server...
Parameters: {"utf8"=>"✓", "authenticity_token"=>"AsGsRHwiVva/+kTrBs0IjLeZwj1ZmXBuKZr9Pg/N6Xk=", "discussion"=>{"shortdesc"=>"Talk about something.", "content"=>"Try to update check box.", "resolved"=>"1"}, "commit"=>"Update Discussion", "id"=>"1"}
But the query doesn't include anything about updating that field.
AREL (14.9ms) UPDATE "discussions" SET "content" = 'Try to update check box.', "updated_at" = '2011-07-18 17:53:50.783176' WHERE "discussions"."id" = 1
Any idea on what I'm missing?
There are 4 reasons why this could be happening:
resolved is already set to true in the database.
You defined the resolved= method in your model and it no longer sets the attribute.
You have attr_protected :resolved.
You have attr_accessible but do not have :resolved in the list.
does your boolean column have a default? If it defaults to true - rails might not bother adding it to the set of attributes.
Alternatively, have you got attr_protected set for that column? if so - rails will never add that field to the attributes using update_attributes. You'll need to do that manually.
All,
I had recently begun rails and was taking over someone else's code and found another scenario that was not covered here that was getting me.
When using the style pointed to by this link, the params are formed in a separate method. I had to update the "_params" method to add it to the allowable list.
http://edgeapi.rubyonrails.org/classes/ActionController/StrongParameters.html
Are you sure that the element is sended it?
I mean, form element without checked the element are not sended, so you have to put an hidden checkbox for default false.

Resources