【问题标题】:ROR: Collection select with with include_blank won't allow nilROR:带有 include_blank 的集合选择不允许 nil
【发布时间】:2016-11-26 21:14:21
【问题描述】:

我的表单中有一个集合选择:

<div class="field">
    <%= f.label :area %>
    <%= f.collection_select(:area_id, Area.all, :id, :name, include_blank: "No area.") %>

而且我的模型验证对区域没有要求。

据我了解,使用 include_blank 可以让我选择 nil。但是我收到一个验证错误“区域必须存在”

编辑:

这是模型中的重要代码:

has_many :ratings, dependent: :destroy
has_many :noise_ratings, dependent: :destroy
has_many :statuses, dependent: :destroy
has_many :checkins, dependent: :destroy

has_and_belongs_to_many :features

belongs_to :area
belongs_to :campus

validates :name, presence: true, uniqueness: { scope: :campus_id, message: "unique space for each campus." }
validates :description, presence: true
validates :campus_id, presence: true

【问题讨论】:

  • 请将您的模型添加到问题中
  • 你在使用 rails 5 吗?我记得在 rails 5 中需要使用 belongs_to 关联,除非你指定 required: false 或类似的东西,我不记得了。
  • 我正在使用 Rails 5
  • 好的,所以,解决方法是指定belongs_to :area,可选:true,以防你想拥有那种数据。添加它是为了防止数据不一致。
  • 在 Rails 5 中 belongs_to 关联要求关联对象存在。请参阅discussion about this new feature。

标签: ruby-on-rails ruby forms collection-select


【解决方案1】:

Rails 5 强制您设置所有 belongs_to 关联,除非您指定 optional: true。添加它是为了防止数据不一致,因此,如果您希望它的行为与以前的 Rails 版本一样,您只需将关联更改为:

belongs_to :area, optional: true

【讨论】:

    【解决方案2】:

    在 Rails 5 中,默认设置为 true。请查看 belongs_to 文档中的 :optional 和 :required 选项以获取更多详细信息。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-19
      • 2019-10-30
      • 2023-01-19
      • 2011-07-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多