【问题标题】:rails set default value for associationrails 设置关联的默认值
【发布时间】:2016-10-19 15:47:32
【问题描述】:

在我的第一个 Rails (5) 应用程序中,我想在创建时为关联设置默认值。已阅读有关 SO 的文档和许多问题,但找不到答案。

我使用after_initialize :set_default_values 并想为documenttype 设置默认值

def set_default_values
    unless persisted?
        self.documenttype || 1  if self.documenttype.nil?
        self.dateformat ||= 'dd.mm.yyyy' if self.dateformat.nil?
    end
end

【问题讨论】:

  • 你忘记了= 符号:self.documenttype ||= 1

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


【解决方案1】:

我认为您在这里缺少=

self.documenttype || 1  if self.documenttype.nil?

应该是这样的

self.documenttype ||= build_documenttype

或针对特定的文档类型:

self.documenttype ||= Documenttype.find(1)

编辑: 在评论 OP 中提到 documenttype 是一个 has_one 关联。

【讨论】:

  • 添加= 符号无法解决;然后它会呈现一个错误Documenttype(#70289997518120) expected, got Fixnum(#70289925178420)
  • 所以 documenttype 期望一个不同类型的对象(Documenttype)并且你试图把默认值 1,所以这个错误。 documenttype 是什么变量?如果可以给我一些更详细的信息,那么我可能会提供帮助
  • 它是一个 has_one 关联
  • 试试self.documenttype ||= build_documenttype,如果有帮助,我会更新我的答案
  • 以及如何添加我想要的默认文档类型?
猜你喜欢
  • 2021-06-19
  • 2015-05-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-05
  • 1970-01-01
相关资源
最近更新 更多