【问题标题】:Error displaying select field from enum on model在模型上显示从枚举中选择字段时出错
【发布时间】: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 =&gt; :select, :collection =&gt; Plant.life_cycle.keys.to_a 的表单
  • 我认为应该是life_cycles。我在回答中更改了它。获取此类信息的一个好方法是在 Plant 类上调用方法 methods(例如在 live shell 中)。

标签: ruby-on-rails enums haml


【解决方案1】:

我在我的一个表单中做了类似的事情(使用simple_form):

= f.select :life_cycle, Plant.life_cycles.keys

【讨论】:

    【解决方案2】:

    答案前的几个例子

    # 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

    【讨论】:

    • ug,复数!还没有完全习惯。很高兴知道这是我唯一做错的事情。谢谢
    猜你喜欢
    • 2011-09-14
    • 2019-07-15
    • 2016-07-03
    • 2018-04-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-29
    • 1970-01-01
    相关资源
    最近更新 更多