Ruby on Rails,使用同名枚举的问题

bogh5gae  于 2023-10-17  发布在  Ruby
关注(0)|答案(2)|浏览(151)

下面是我的一些下拉视图:

<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.如何解决这样的冲突?

3b6akqbq

3b6akqbq1#

当需要定义多个具有相同值的枚举时,可以使用:_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

kkbh8khc

kkbh8khc2#

首先,就像Marek Lipka说的,你应该使用布尔值来处理你的情况。
如果你需要用相同的条目定义不同的枚举,我建议使用gem 'enumerize'(https://github.com/brainspec/enumerize)。

更新

Enum(https://api.rubyonrails.org/classes/ActiveRecord/Enum.html)在最近的Rails中得到了支持,我们应该使用它。

相关问题