Ruby on Rails – 需要一个创意

huangapple go评论59阅读模式
英文:

Ruby on Rails - need an idea

问题

我需要一个建议,或者更好地称之为想法。 Ruby on Rails – 需要一个创意

想象一下,你有一个类,让我们称之为Tree。树生长在不同的国家,但对于其中一些国家来说,它们是本土的,而对于其中一些国家来说,它们不是。

我需要找到将Tree与Country连接起来的最佳方法,以便对于每个国家,同一个实例将具有不同的值。比如,例如,松树在加拿大的本土设置为true,但在埃及不是,等等。

我知道我可以有多条记录,但我更愿意找到一种平滑和漂亮的解决方案,避免为一个实例创建成千上万的记录。

目前,我只需要一些想法。

英文:

I need an advice or maybe better to call it idea. Ruby on Rails – 需要一个创意

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, but
  • tree.native_countries would only return countries in which the tree is native.

huangapple
  • 本文由 发表于 2023年3月9日 16:18:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/75681964.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定