HABTM Tables 2 2 different relationships

I have a table of service types containing the identifier and name of several dozen services.

I have a project table that should have a list of services offered and a list of accepted services.

I know that I would use HABTM on both sides with a project_service_types table between them.

I cannot figure out what to do when I have 2 different relationships between the same table. I suspect it uses: join_table and: associated_forign_key, but I cannot get it to work in my application.

thanks.

+3
source share
3 answers

habtm, , , has_many: through. . , .

, "" . , . .

create_table :project_services do |t|
  t.references :project
  t.references :service_type
  t.string :status
end

class ProjectService < ActiveRecord::Base
  belongs_to :project
  belongs_to :service
end

class Project < ActiveRecord::Base
  has_many :project_services
  has_many :accepted_services, :through => :project_services,
    :conditions => { :status => 'accepted' }
  has_many :proposed_services, :through => :proposed_services,
    :conditions => { :status => 'proposed' }
end

class Service < ActiveRecord::Base
  has_many :project_services
  has_many :accepted_projects, :through => :project_services,
    :conditions => { :status => 'accepted' }
  has_many :proposed_projects, :through => :proposed_services,
    :conditions => { :status => 'proposed' }
end
+4

HABTM...

class ServiceType < ActiveRecord::Base
  has_and_belongs_to_many :accepted_projects, :class_name => "Project", :join_table => :projects_accepted_types
  has_and_belongs_to_many :proposed_projects, :class_name => "Project", :join_table => :projects_proposed_types
end

class Project < ActiveRecord::Base
  has_and_belongs_to_many :accepted_types, :class_name => "ServiceType", :join_table => :projects_accepted_types
  has_and_belongs_to_many :proposed_types, :class_name => "ServiceType", :join_table => :projects_proposed_types
end
+5

, , has_many: :

class ProposedService < ActiveRecord::Base
    belongs_to :project
    belongs_to :service_type

class AcceptedService < ActiveRecord::Base
    belongs_to :project
    belongs_to :service_type

class Projects < ActiveRecord::Base
    has_many :proposed_services
    has_many :accepted_services
    has_many :service_types, :through => :proposed_services
    has_many :service_types, :through => :accepted_services

class ServiceTypes < ActiveRecord::Base
    has_many :proposed_services
    has_many :accepted_services
    has_many :projects, :through => :proposed_services
    has_many :projects, :through => :accepted_services

"--" :

http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html

. , !

+3

Source: https://habr.com/ru/post/1705358/


All Articles