HABTM 2表2种不同的关系

时间:2009-03-25 19:08:17

标签: ruby-on-rails has-and-belongs-to-many

我有一个服务类型表,其中包含几十个服务的ID和名称。

我有一个Projects表,必须有一个Proposed Services列表和一个Accepted Services列表。

我知道我会在两侧使用HABTM,并在其间使用project_service_types表。

当我在同一张桌子之间有两种不同的关系时,我无法弄明白该怎么做。我怀疑它使用:join_table和:associated_forign_key,但我无法在我的应用程序中使用它。

感谢。

3 个答案:

答案 0 :(得分:5)

我用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

答案 1 :(得分:4)

虽然你可以用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

答案 2 :(得分:3)

为此你可能想要使用has_many:through,如:

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

更详细地解释了这一点。希望这有帮助!