【问题标题】:Rails Association Has_One Having Pluralisation Model Name Instead of Singular and not workingRails Association Has_One 具有复数模型名称而不是单数且不工作
【发布时间】:2019-05-28 16:47:51
【问题描述】:

我有一个名为 BigbluebuttonRoom 的模型。

class BigbluebuttonRoom < ActiveRecord::Base
has_one :room_options, :class_name => 'BigbluebuttonRoomOptions'

所以当我调用 room.room_options 时,不会出现任何方法错误。

【问题讨论】:

  • var room 中有什么内容?如果它为零,那么你会得到无方法错误。没有完整的错误日志很难判断。

标签: ruby-on-rails ruby-on-rails-5 associations has-one


【解决方案1】:

为什么你用复数形式命名你的模型BigbluebuttonRoomOptions?打破 Rails 惯例是个坏主意。模型名称应为单数形式,BigbluebuttonRoomOption。更改它和相应的文件名。

另外,has_one 的约定也是单数形式。应该是:

has_one :room_option, :class_name => 'BigbluebuttonRoomOption'

【讨论】:

  • 在某些情况下,您可能需要 has_one 的复数形式,例如has_one :preferences, class: 'User::Preferences' 其中单个记录具有每个首选项的列。然后变成:user.preferences.something_enabled?.
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-03-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-17
相关资源
最近更新 更多