2013-08-21 50 views
0

我正在尝试在用户和树列表之间创建一个关联。但对于这个应用程序,客户关心的是树木是否与院子或社区相关联。Rails Model Association

因此,例如 - 如果他们去在他们的“院子里”创建一棵松树榆树 ,并在“邻居”松树和棕榈树。

我希望有一个单一的松树元素,但我想打电话给像 - user.yard_trees和tree.neighborhood_trees -

感谢您的帮助。

回答

1

你可以做这样的事情

class User < ActiveRecord::Base 
    has_many :yard_trees, class_name: 'Tree', foreign_key: 'yard_id' 
    has_many :neighborhood_trees, class_name: 'Tree', foreign_key: 'neighborhood_id' 
end 

class Tree < ActiveRecord::Base 
    belongs_to :neighborhood, class_name: 'User' 
    belongs_to :yard, class_name: 'User' 
end 

如预期,如果你的表是树立正确这应该工作。但这对我来说似乎很奇怪。如果我是你,我会实际创建堆场及周边环境模型,并将其设置是这样的:

class User < ActiveRecord::Base 
    has_one :yard 
    has_one :neighborhood 
end 

class Tree < ActiveRecord::Base 
    has_and_belongs_to_many :yards 
    has_and_belongs_to_many :neighborhoods 
end 

class Neighborhood < ActiveRecord::Base 
    has_and_belongs_to_many :trees 
    belongs_to :user 
end 

class Yard < ActiveRecord::Base 
    has_and_belongs_to_many :trees 
    belongs_to :user 
end 

编辑:

has_and_belongs_to_many可能更适合。这样你就可以拥有一棵松树对象并将它与许多场地和社区相关联。