[英]How do I do two has_many/belongs_to relationships between two models?
I've got a Project
model, and a Contact
model. 我有一个Project
模型和一个Contact
模型。 The Project model has an owner and a client, both of which are Contact
s. Project模型有一个所有者和一个客户端,两者都是Contact
。 I've obviously got something ambiguous going on, because if I have a contact and ask for its projects, Rails won't know whether I'm asking for it's projects where it's the client or where it's the owner. 我显然有些模棱两可的事情,因为如果我有一个联系人并要求它的项目,Rails将无法知道我是否要求它的项目在哪里是客户端或者它是所有者。 So far I've got this: 到目前为止,我有这个:
class Contact < ActiveRecord::Base
has_many :projects
end
class Project < ActiveRecord::Base
belongs_to :owner, :class_name => 'Contact', :foreign_key => 'owner_id'
belongs_to :client, :class_name => 'Contact', :foreign_key => 'client_id'
end
How do I make two relationships here? 我如何在这里建立两种关系?
Its similar to the way belongs_to
is defined in the other class. 它类似于belongs_to
的方式在另一个类中定义。
So Basically 所以基本上
class Contact < ActiveRecord::Base
has_many :projects_owned, :class_name => "Project", :foreign_key => "owner_id"
has_many :projects_as_client, :class_name => "Project", :foreign_key => "client_id"
end
names of associations could be better. 协会的名称可能会更好。 The Single Table inheritance approach described before me is also a neat way, but go for it if you have a lot of different behaviour for each of the OwnerContact and ClientContact class, otherwise it might be just a useless overhead. 我之前描述的单表继承方法也是一种简洁的方法,但是如果你对每个OwnerContact和ClientContact类有很多不同的行为,那就去做吧,否则它可能只是一个无用的开销。
I think here's should be polymorphic association, something like this 我认为这应该是多态关联,就像这样
class Owner < ActiveRecord::Base
has_many :projects, :as => :person
end
class Client < ActiveRecord::Base
has_many :projects, :as => :person
end
class Project < ActiveRecord::Base
belongs_to :person, :polymorphic => true
end
Now you can retrieve projects by @client.projects
or @owner.projects
. 现在您可以通过@client.projects
或@owner.projects
检索项目。 If you want to get person from @project you should add to Project migration this: 如果你想从@project获取人员,你应该添加到Project migration:
class CreateProjects < ActiveRecord::Migration
def self.up
create_table :projects do |t|
t.references :person, :polymorphic => true
t.timestamps
end
end
...
You should try to use a single table inheritance on the Contact table. 您应该尝试在Contact表上使用单个表继承。 All you need to do for this to work is to implement a 'type' column (string). 您需要做的就是实现'type'列(字符串)。 Rails will handle the rest Rails将处理剩下的事情
class Contact < ActiveRecord::Base
# implement a type column
has_many :projects
end
class OwnerContact < Contact
end
class ClientContact < Contact
end
class Project < ActiveRecord::Base
belongs_to :owner, :class_name => 'OwnerContact'
belongs_to :client, :class_name => 'ClientContact'
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.