2016-04-21 58 views
3

這裏的問題是一些降在我看來倒:Ruby on Rails的,用枚舉同名

<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.如何解決這樣的衝突?

+1

使用布爾值來代替。這些字段沒有理由成爲枚舉。 –

回答

1

首先,就像馬立克說Lipka的,你應該使用布爾值來處理您的案件。

如果您需要定義具有相同的條目不同的枚舉,我建議使用寶石「enumerize」(https://github.com/brainspec/enumerize)來代替。

6

可以使用:_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