【问题标题】:Ruby, Retrieve Child Object By KeyRuby,按键检索子对象
【发布时间】:2012-01-12 03:28:31
【问题描述】:

我正在尝试根据其父表中的键检索子对象。例如,我有 Customer 类,其中包含 Stores 表的“store_id”键。如果客户有一个“store_id”键,我想带回那个 Store 对象而不是父 Customer 对象。

编辑:这是一个 sql 语句,显示我正在尝试做的事情。

所以 SQL 语句看起来像这样。

"SELECT storeS.* FROM customers INNER JOIN stores ON customers.store_id = storeS.id WHERE customers.id = '9'"

我知道 sql 可能是错误的,但这是一种非常简洁的显示方式。

【问题讨论】:

  • “带回来”是什么意思?您能否向我们展示一些您正在尝试做的示例代码?
  • @Mischa SQL 语句看起来像这样。
  • 如果这是你想要的,你应该按照 PinnyM 的回答。

标签: ruby ruby-on-rails-3 activerecord join inner-join


【解决方案1】:

我假设您正在使用带有开箱即用配置的 Rails(使用 ActiveRecord)。

按照惯例,“customers”表中的“store_id”键应与“stores”表中的“id”字段匹配。您还应该有以下类模型设置:

class Store < ActiveRecord::Base
  has_many :customers # this is not required for what you want to do here, but recommended
end

class Customer < ActiveRecord::Base
  belongs_to :store
end

假设这是真的,如果你有存储密钥,你可以这样做:

# assuming we have store key == 9
Store.find(key)

如果您已经有客户,您也可以这样做:

# assuming we have customer.store_id == 9
customer.store

或者,如果您只有客户密钥:

# assuming we have a customer key == 9
customer = Customer.find(9)
store = customer.store

【讨论】:

  • 请注意,要使 customer.store 工作,您需要在 Customer 模型上定义 belongs_to :store
  • @PinnyM 我已经编辑了原始帖子以包含一个 sql 语句来显示我在做什么。为了澄清起见,我通常只假设我有一个 customer.id。
  • 如果您使用默认设置的 Rails(ActiveRecord 作为 ORM),则根本不需要编写任何 SQL。我已经编辑了我的答案以显示应该如何编写。
  • @PinnyM 谢谢 PinnyM !我希望我必须“触摸” Customer 对象,但我是 Rails 新手,所以我目前正在学习摒弃旧的做事方式。
【解决方案2】:

我不经常使用 ActiveRecord,但我认为是这样的:

Store.find(customer.store_id)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-09-27
    • 1970-01-01
    • 1970-01-01
    • 2014-12-16
    • 2019-08-12
    • 2013-04-02
    • 2013-11-15
    相关资源
    最近更新 更多