【问题标题】:Ruby on Rails, issues using enum with same nameRuby on Rails,使用同名枚举的问题
【发布时间】:2016-08-14 06:03:01
【问题描述】:

这是我认为的一些下拉列表:

<div class="col-xs-3">
    <%= f.select(:require_booking, get_advance_booking.collect {|p| [ p[:require_booking], p[:require_booking] ] }, {include_blank: false} , :class => 'form-control') %>
</div>

<div class="col-xs-3">
    <%= f.select(:instant_booking, get_instant_booking.collect {|p| [ p[:instant_booking], p[:instant_booking] ] }, {include_blank: false} , :class => 'form-control') %>
</div>

这是我的application_helper.rb

  def get_advance_booking
    ret = [{:require_booking => 'No'},{:require_booking => 'Yes'}]
  end

 def get_instant_booking
    ret = [{:instant_booking => 'No'},{:instant_booking => 'Yes'}]
  end

但现在的问题是,在我的模型 product.rb 中,我无法设置具有相同名称的枚举:

class Product < ActiveRecord::Base
    enum require_booking: {
        No: 0,
        Yes: 1
    }
    enum instant_booking: {
        No: 0,
        Yes: 1
    }
end

我收到的错误是You tried to define an enum named "instant_booking" on the model "Product", but this will generate a instance method "No?", which is already defined by another enum. 如何解决这样的冲突?

【问题讨论】:

  • 使用布尔值代替。这些字段没有理由是枚举。

标签: ruby-on-rails ruby enums


【解决方案1】:

当您需要定义具有相同值的多个枚举时,可以使用 :_prefix 或 :_suffix 选项。如果传递的值为 true,则方法以枚举名称为前缀/后缀。也可以提供自定义值:

class Conversation < ActiveRecord::Base
  enum status: [:active, :archived], _suffix: true
  enum comments_status: [:active, :inactive], _prefix: :comments
 end

来源:http://edgeapi.rubyonrails.org/classes/ActiveRecord/Enum.html

【讨论】:

  • 谢谢!哇。我不小心删除了一些模型文件并运行了迁移。在那之后,我无法重新启动任何东西,因为我收到了关于之前创建枚举的错误。我在所有这些上都使用了 _suffix: true ,现在正在工作。谢谢你。
【解决方案2】:

首先,就像 Marek Lipka 所说,您应该使用布尔值来处理您的情况。

如果您需要定义具有相同条目的不同枚举,我建议使用 gem 'enumerize' (https://github.com/brainspec/enumerize) 代替。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-05
    • 2016-07-27
    • 2016-02-23
    相关资源
    最近更新 更多