【发布时间】:2017-02-06 10:28:58
【问题描述】:
当我尝试从我的模型中显示枚举的选择下拉列表时,我遇到了错误。
我在我的模型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
当我尝试访问编辑页面时,我收到“未定义方法”错误。我对 ruby 很陌生,所以我可能误解了一些简单的东西......
谢谢
【问题讨论】:
-
我只是不清楚语法。我只需要在
= render 'form'行前面加上= f.select ...吗?在那种情况下,我看不出f指的是什么。有什么理由认为'form'会呈现不同的效果? -
= render 'form'只不过是部分_form.html.haml,其中包含您需要放置= f.input :life_cycle, :as => :select, :collection => Plant.life_cycle.keys.to_a的表单 -
我认为应该是
life_cycles。我在回答中更改了它。获取此类信息的一个好方法是在Plant类上调用方法methods(例如在 live shell 中)。
标签: ruby-on-rails enums haml