【问题标题】:Rails, MongoMapper nested Array in HAML form troubleRails, MongoMapper 嵌套数组在 HAML 表单中的麻烦
【发布时间】:2012-09-30 06:02:20
【问题描述】:

我明白了

# 的未定义方法 `Carrots'(引用 ln#18)

尝试使用以下表单进行编辑时:

= form_for @harvest do |f|
  - if @harvest.errors.any?
    #error_explanation
      %h2= "#{pluralize(@harvest.errors.count, "error")} prohibited this harvest from being saved:"
      %ul
        - @harvest.errors.full_messages.each do |msg|
          %li= msg

  .field
    = f.label :created_at
    = f.text_field :created_at, :disabled => true
    %br
    = f.label :photo
    = f.text_field :photo
    %h2 Crops
    - @harvest.harvested_crops.each do |harvested_crop|
      = f.label :harvested_crop['crop']
      = f.select harvested_crop['crop'], Crop.all.collect {|p| [ p.name, p.id ] }, {:include_blank => ''}
      = f.label :harvested_crop['amount']
      = f.text_field harvested_crop['amount']

  %br
  .actions
    = f.submit 'Save'

使用以下数据:

{ "_id" : ObjectId("5067846f37bca62bccc3729e"), "user_id" : "5067844637bca62bccc3729c", "photo" : "carrotsnspuds.jpg", "harvested_crops" : [    {   "crop" : "Carrots",     "amount" : 1112.15 },   {   "crop" : "Potatoes",    "amount" : 3212.44 } ] }

我已经为 MongoMapper、Rails 和 Embedded 文档尝试了相关的 Stack Overflow 问题,但我没有任何运气,可能是因为这是一个嵌套数组而不是 EmbeddedDocument。我还没有使用 Formtastic 或任何东西,只是想先了解这里所需的语法。

【问题讨论】:

    标签: ruby-on-rails forms mongodb haml


    【解决方案1】:

    这绝对没有效率,但这让我能够完成工作:

    = form_for @harvest do |f|
      - if @harvest.errors.any?
        #error_explanation
          %h2= "#{pluralize(@harvest.errors.count, "error")} prohibited this harvest from being saved:"
          %ul
            - @harvest.errors.full_messages.each do |msg|
              %li= msg
    
      .field
        = f.label :created_at
        = f.text_field :created_at, :disabled => true
        %br
        = f.label :photo
        = f.text_field :photo
        %h2 Crops
        - x = 0
        - @harvest.harvested_crops.each do |harvested_crop|
          = f.fields_for "harvested_crops[]", harvested_crop do |hc|
            %b Harvested Crop
            %select{:name => "harvest[harvested_crops][" + x.to_s + "][crop]"}
              - Crop.all.collect.each do |crop_name|
                - if harvested_crop['crop'] == crop_name[:name]
                  %option{:selected => "selected", :value => crop_name[:name]}
                    = crop_name[:name]
                - else
                  %option{:value => crop_name[:name]}
                    = crop_name[:name]
            %b Amount
            %input{:name => "harvest[harvested_crops][" + x.to_s + "][amount]", :value => harvested_crop['amount']}/
            %br
            - x += 1
    
      %br
      .actions
        = f.submit 'Save'
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-13
      • 2017-05-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多