jma*_*erx 9 ruby enums ruby-on-rails
我需要做这样的事情:
class PlanetEdge < ActiveRecord::Base
enum :first_planet [ :earth, :mars, :jupiter]
enum :second_planet [ :earth, :mars, :jupiter]
end
Run Code Online (Sandbox Code Playgroud)
我的表是一个边的表,但每个顶点是一个整数.
然而,似乎在铁轨中不可能出现这种情况.什么可能是制作字符串列的替代方法?
Woj*_*ski 10
如果您按照http://edgeapi.rubyonrails.org/classes/ActiveRecord/Enum.html运行rails 5.0或更高版本
当您需要定义具有相同值的多个枚举时,可以使用:_prefix或:_suffix选项.如果传递的值为true,则方法的前缀/后缀为枚举的名称.也可以提供自定义值:
class Conversation < ActiveRecord::Base
enum status: [:active, :archived], _suffix: true
enum comments_status: [:active, :inactive], _prefix: :comments
end
Run Code Online (Sandbox Code Playgroud)
在上面的例子中,bang和谓词方法以及相关的范围现在都是相应的前缀和/或后缀:
conversation.active_status!
conversation.archived_status? # => false
conversation.comments_inactive!
conversation.comments_active? # => false
Run Code Online (Sandbox Code Playgroud)
也许它可以将行星提取为另一个模型?
class Planet < ActiveRecord::Base
enum type: %w(earth mars jupiter)
end
class PlanetEdge < ActiveRecord::Base
belongs_to :first_planet, class_name: 'Planet'
belongs_to :second_planet, class_name: 'Planet'
end
Run Code Online (Sandbox Code Playgroud)
您可以使用以下命令创建 PlanetEdge accepts_nested_attributes_for:
class PlanetEdge < ActiveRecord::Base
belongs_to :first_planet, class_name: 'Planet'
belongs_to :second_planet, class_name: 'Planet'
accepts_nested_attributes_for :first_planet
accepts_nested_attributes_for :second_planet
end
PlanetEdge.create(
first_planet_attributes: { type: 'mars' },
second_planet_attributes: { type: 'jupiter' }
)
Run Code Online (Sandbox Code Playgroud)