【问题标题】:How Should I Build a has_one through Association?我应该如何通过关联建立 has_one?
【发布时间】:2013-10-28 15:19:28
【问题描述】:

对于has_one 关联,我可以建立这样的关联:

foo.build_bar()

我应该如何建立has_one, through: 关联?

例如:

class Foo

  has_one :bar
  has_one :baz, through: :bar

end

我应该如何构建baz?在这个例子中,foo.build_baz 给我一个No Method Error

文档here 说:

当你声明一个 has_one 关联时,声明类 自动获取关联相关的四个方法:

association(force_reload = false)
association=(associate)
build_association(attributes = {})
create_association(attributes = {})

然而,情况似乎并非如此。使用 Pry 内省 Foo 的实例我可以看到没有添加这样的方法,因为它会在没有 through:has_one 上添加。

【问题讨论】:

  • has_one 后面的has_one: :bar 是不是错字?
  • bar和baz是什么关系?

标签: ruby-on-rails ruby-on-rails-3 associations has-one-through


【解决方案1】:

似乎一种可能性是:

foo.build_bar().build_baz()
foo.save!

【讨论】:

  • 这确实有效。我发现你在问题中的论点更有说服力。 IOW,这不应该被认为是rails中的一个错误,因为has_one在使用through时不会生成这些方法?
  • 如果您不想违反得墨忒耳法则,那么您可以将build_baz 委托给bardelegate :build_baz, to: :bar
猜你喜欢
  • 2017-11-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多