Tag Archives: model

Rails: validates values from db

Example: we have POST form, which has

1
<select>

options, the values for these options we get from db, something like:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<div id="new_form">
<%= form_tag(controller: "jobs", action: "create", method: "post") do %>
  <h2>Choose Territory</h2>
  <%= collection_select(:job, :territory_id, Territory.all, :id, :name) %>

  <h2>Choose Server</h2>
  <%= collection_select(:job, :server_id, Server.all, :id, :name) %>

  <h2>Choose Job type</h2>
  <%= collection_select(:job, :jobtype_id, Jobtype.all, :id, :name) %>

  <h2>Enter Version</h2>
  <%= text_field(:job, :version, size: 12) %>
  <p>
    <%=  submit_tag("Add Job") %>
  </p>
<% end %>
</div>

And we would like to be sure that values which gets by destination url are fine, then we have to create validates for these data, let's go:
add new file to «conserns», I named it get_all_ids.rb:

1
2
3
4
5
module GetAllIds extend ActiveSupport::Concern
  def self.ids
    all.collect { |record| record.id }
  endg
end

then include that «concern» to model

1
2
3
class Territory < ActiveRecord::Base
  include GetAllIds
end

I have added it to models Territory, Jobtype and Server

And the last step is adding validates to destination model:

1
2
3
4
5
  validates :territory_id, :jobtype_id, :server_id, :version, presence: true
  validates :version, format: { with: /[0-9]\.[0-9]\.[0-9]{2}\.[0-9]{1,3}(\.[0-9]{1,3})?/, message: "Version number have to contains from numbers and '.' only !"}
  validates :territory_id, inclusion: Territory.ids
  validates :jobtype_id, inclusion: Jobtype.ids
  validates :server_id, inclusion: Server.ids

The last 3 validates are checks for our data.

Rails: model conception

You should create new model for each table:
rails generate model Tank

it'll create migration Tanks, you should open db/migrate/${date}_create_tanks.rb

and put there definition of table

After you should open modelĀ  app/models/tank.rb

and put there tables relations.

After creating models you should use RAILS_ENV=development rake db:migrate for creating database with tables and relations between the last one