Ruby/Rails lentelių asociacijos

Iš Wikibooks.
Jump to navigation Jump to search
# projects(id, title)
# tasks(id, project_id, title)

Project
  has_many :tasks
Task
  belongs_to :project


Kai turime daug su daug sąryšį:

has_and_belongs_to_many


class Project < ActiveRecord::Base
  belongs_to :portfolio
  has_one    :project_manager
  has_many   :milestones
end

Our project objects are now able to respond to methods such as project.portfolio, project.has_project_manager?, and project.create_in_milestones("deadline" => Date.today + 5).


But how do we represent many-to-many relationships? Currently, it has the slightly clumsy macro of has_and_belongs_to_many, as illustrated below:

class Project < ActiveRecord::Base
  has_and_belongs_to_many :categories
end
project.add_categories(critical, technical)
project.categories_count
project.has_categories?