Table of Contents
Belongs_to / has_many
# == Schema Information # # Table name: emergencies # # id :integer not null, primary key # activated_by_id :integer # # Indexes # # index_emergencies_on_activated_by_id (activated_by_id) class Emergency < ActiveRecord::Base belongs_to :activated_by, primary_key: 'id', foreign_key: 'activated_by_id', class_name: 'Company' end
# == Schema Information # # Table name: companies # # id :integer not null, primary key # name :string class Company < ActiveRecord::Base has_many :emergencies, primary_key: 'id', foreign_key: 'activated_by_id', class_name: 'Emergency' validates :name, presence: true, uniqueness: true end
Emergency.first.activated_by.name Company.first.emergencies
Area has_many loops Loop belongs_to Area
# loop/index.html.erb <td><%= loop.area.name %></td>
# area/_form.heml.erb <div class="field"> <%= f.label :area_id %><br> <%= f.select :area_id, Area.all.map { |area| [area.name, area.id] }, include_blank: true %> </div>
Has_and_belongs_to_many
Source: http://apidock.com/rails/ActiveRecord/Associations/ClassMethods/has_and_belongs_to_many
# == Schema Information # # Table name: loops # # id :integer not null, primary key # name :string # coord_x :decimal(, ) # coord_y :decimal(, ) # created_at :datetime # updated_at :datetime # area_id :integer class Loop < ActiveRecord::Base has_and_belongs_to_many :gates belongs_to :area has_many :emergencies validates :name, presence: true, uniqueness: true end
# == Schema Information # # Table name: gates # # id :integer not null, primary key # name :string # coord_x :decimal(, ) # coord_y :decimal(, ) # created_at :datetime # updated_at :datetime # class Gate < ActiveRecord::Base has_and_belongs_to_many :loops validates :name, presence: true, uniqueness: true end
l = Loop.first l.gates << Gate.first
# loops/_add_gates.html.erb <h3>Add gates</h3> <%= form_tag loops_path do %> <div class="field"> <%= label_tag :gate %> <%= collection_select :gate, :id, Gate.all, :id, :name, include_blank: true %> </div> <div class="actions"> <%= submit_tag %> </div> <% end %>
has_many through --- uniq clause
class Project < ActiveRecord::Base validates :name, presence: true, uniqueness: true has_many :activities has_many :tasks, -> { uniq }, through: :activities has_many :users, -> { uniq }, through: :activities scope :how_many_new_activity, -> { limit(5) } end