【问题标题】:Rails 5 has_many and belongs_to : how to get the top level idRails 5 has_many 和 belongs_to :如何获取顶级 id
【发布时间】:2018-07-23 22:58:42
【问题描述】:

以下:

class Author < ApplicationRecord
  has_many :books
end


class Book < ApplicationRecord
  belongs_to :author
end

如果我有电话:

book.author.method1

是否可以在方法 1 中获取书籍 ID(或任何对象的数据)? (无需作为参数传入)

【问题讨论】:

  • method1 的本质是什么?也许让method1 成为book 上的方法而不是author 是有意义的。

标签: ruby-on-rails activerecord ruby-on-rails-5


【解决方案1】:

我认为你不能在不传入父模型的情况下访问子 ID,因为它是一个 has_many 关系。似乎您必须执行以下操作:

book.author.method1(book.id)

当然你也可以只传递整个对象。

根据方法的作用,也许它更适合书籍模型?

【讨论】:

  • 我现在正在做类似的事情(传递对象)。只是感觉有点“啰嗦”。
  • 如果感觉不对,很可能。如果没有更多上下文,我会回应 @jvillian 的建议,将方法放在 book 上。
【解决方案2】:

基于cmets,重新思考。

author = book.author
author.method1(book)

这比我的干净多了。

(感谢反馈/cmets)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-10
    • 2014-10-23
    相关资源
    最近更新 更多