Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby on Rails, issues using enum with same name

Here is some of the drop down in my view:

<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>

and

<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>

and here is my 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

But now the issue is, in my model product.rb, I can't set enum with same name:

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

The error that I receive is 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. How to resolve such a conflicts?

like image 929
d3bug3r Avatar asked Apr 21 '16 07:04

d3bug3r


1 Answers

You can use the :_prefix or :_suffix options when you need to define multiple enums with same values. If the passed value is true, the methods are prefixed/suffixed with the name of the enum. It is also possible to supply a custom value:

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

source :http://edgeapi.rubyonrails.org/classes/ActiveRecord/Enum.html

like image 148
ashwintastic Avatar answered Nov 06 '22 12:11

ashwintastic