英文:
Ruby on Rails - need an idea
问题
我需要一个建议,或者更好地称之为想法。
想象一下,你有一个类,让我们称之为Tree。树生长在不同的国家,但对于其中一些国家来说,它们是本土的,而对于其中一些国家来说,它们不是。
我需要找到将Tree与Country连接起来的最佳方法,以便对于每个国家,同一个实例将具有不同的值。比如,例如,松树在加拿大的本土设置为true,但在埃及不是,等等。
我知道我可以有多条记录,但我更愿意找到一种平滑和漂亮的解决方案,避免为一个实例创建成千上万的记录。
目前,我只需要一些想法。
英文:
I need an advice or maybe better to call it idea.
Imagine you have an class, lets call it Tree. Trees are in different countries but for some of them there are native and for some there are not.
I need the best way how to connect Tree with Country so for each country same Instance will have different values. Like for example pine will have native set as true for Canada, but not for Egypt, etc.
I know that I can have multiple records, but I'd rather prefer some smooth and pretty solution with avoidance of creating thousands of records for one Instance.
For now I need just an ideas.
答案1
得分: 2
我会像这样建模:
class Tree
has_many :tree_locations
has_many :countries, through: :tree_locations
has_many :native_tree_locations, class_name: 'TreeLocation',
-> { where(native: true) }
has_many :native_countries, through: :native_tree_locations,
class_name: 'Country'
end
class TreeLocation
belongs_to :tree
belongs_to :country
# 数据库中还有一个 `native` 布尔标志
class Country
has_many :tree_locations
has_many :trees, through: :tree_locations
# ...
这允许对于给定的 tree
:
tree.countries
会返回树生长的所有国家,但tree.native_countries
仅返回树原产的国家。
英文:
I would model it like this:
class Tree
has_many :tree_locations
has_many :countries, through: :tree_locations
has_many :native_tree_locations, class_name: 'TreeLocation',
-> { where(native: true) }
has_many :native_countries, through: :native_tree_locations,
class_name: 'country'
class TreeLocation
belongs_to :tree
belongs_to :country
# and a `native` boolean flag in the DB
class Country
has_many :tree_locations
has_many :trees, through: :tree_locations
# ...
This allows for a given tree
:
tree.countries
would return all countries in which the tree grows, buttree.native_countries
would only return countries in which the tree is native.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论