【问题标题】:Has many conditions in Rails 4在 Rails 4 中有很多条件
【发布时间】:2023-04-04 15:08:01
【问题描述】:

如何做到这一点:

 has_many :space_mappings, -> { where(group_id: group_id) }, through: :category

也就是说 - SpaceMapping 和这个模型都有一个 group_id 并且它们必须匹配。我可以只做一个方法,但我希望这成为可能。

我明白了:

undefined local variable or method `group_id' for #<ActiveRecord::Relation::ActiveRecord_Relation_SpaceMapping:0x007fe5ac118bd8>

我已经这样做了:

def space_mappings
  category.space_mappings.where(space_id: Space.where(group_id: group_id))
end

提前致谢。

【问题讨论】:

  • 你想在这里完成什么?只是为了有一个名为 space_mappings 的关联是类别?
  • “这个模型”是否与类别有belongs_to 关系,并且在其表上具有category_id 字段?
  • 我在问这个问题时犯了一个严重的错误。 Category_id 应该是 group_id。很抱歉造成混乱。
  • 这比它澄清的更模糊。什么是group_id?大概是……某事的外键?
  • 嗯...这个模型通过Category模型有很多SpaceMappings。到现在为止还挺好。问题是,要使该关系有效(在应用程序的上下文中), group_id 也必须相同。这有帮助吗?

标签: ruby-on-rails activerecord model-associations


【解决方案1】:

您必须为 category_id 分配一个值。

参见http://guides.rubyonrails.org/association_basics.html(4.3.3.1 部分)。 它可以帮助您理解细节和清晰的概念。

【讨论】:

  • 请再看一遍这个问题——我问错了——现在应该是正确的。对此感到抱歉。
【解决方案2】:

如果“此模型”具有belongs_to :category 关系或has_one :category 关系,那么您根本不需要where 子句。 “有很多通过”的全部意义是将关联模型限制为与它们关联的模型相关联的模型通过

也就是说,你应该能够做到

belongs_to :category
has_many :space_mappings, through: :category

假设空间映射也属于一个类别。

【讨论】:

  • 请再看一遍这个问题——我问错了——现在应该是正确的。对此感到抱歉。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-02-14
  • 2014-12-09
  • 1970-01-01
  • 2014-11-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多