当我尝试从模型中显示精选的枚举下拉列表时,我收到错误。
我在模型Plants
中定义了一个枚举:
class Plant < ActiveRecord::Base
belongs_to :garden
enum life_cycle: [ :annual, :perennial, :biennial ]
enum sun: [ :full_sun, :part_shade, :full_shade ]
enum sow_method: [ :direct, :indoor, :direct_indoor ]
end
我希望相应的输入显示那些枚举选项。我从Saving enum from select in Rails 4.1看到它可以像这样接近(在_form.html.haml
中):
= simple_form_for(@plant) do |f|
= f.error_notification
.form-inputs
= f.input :name
= f.input :scientific_name
= f.input :height
= f.input :width
= f.input :spacing
= f.input :life_cycle, :as => :select, :collection => Plant.life_cycle.keys.to_a
= f.input :sun
= f.input :sow_method
= f.input :direct_seed_start
= f.input :direct_seed_stop
= f.input :indoor_seed_start
= f.input :indoor_seed_stop
= f.input :transplant_start
= f.input :transplant_stop
= f.association :garden
.form-actions
= f.button :submit
当我尝试访问编辑页面时,我得到一个&#34;未定义的方法&#34;错误。我对红宝石很新,所以我可能会误解一些简单的东西...
由于
答案 0 :(得分:0)
我在我的一个表单中做了类似的事情(使用.parentDiv {
display: inline-block;
position: relative;
}
):
simple_form
答案 1 :(得分:0)
答案前的几个例子
# Assume life_cycle was set to 'annual'
puts p.life_cycle
#=> "annual"
p.life_cycle = 0 # set life_cycle as 0
puts p.life_cycle
#=> "annual"
p.life_cycle = 2 # we set to biennial
puts p.life_cycle
#=> "biennial"
您也可以执行此操作,以life_cycle
p.annual? results in true or false
是否为年度
当你这样做时,使用复数的枚举,你可以在类上作为类方法访问它。
puts Plant.life_cycles
{"annual" => 0, "perennial" => 1, "biennial" => 2}
所以是的,因为@razr描述你将使用类方法来获取哈希并提取键以形成你的选择菜单Plant.life_cycles.keys