Helper “fields_for” not working

2019-04-28 00:56发布

I'm using nested attributes, but the fields aren't loaded in my view. Someone know what I missing?

Rails 3.1, Ruby 1.9.2

Model 1:

class Traditions::Material < ActiveRecord::Base
  has_one :material_asset, :dependent => :destroy
  validates_presence_of :title
  accepts_nested_attributes_for :material_asset
end

Model 2:

class Traditions::MaterialAsset < ActiveRecord::Base
  belongs_to :material
  has_attached_file :asset
  validates_attachment_presence :asset
end

View (HAML):

= form_for @material, :html => {:class => 'form', :multipart => true} do |f|
    = errors_for @material

    .field
        = f.label :title
        = f.text_field :title

    .field
        = f.label :description
        = f.text_area :description, :rows => 5

    .field
        = f.fields_for :material_asset do |ma|
            = ma.label :asset
            = ma.file_field :asset

    .buttonrow
        = f.submit 'Save'

Result HTML (part):

<div class='field'></div>
<div class='buttonrow'>
  <input name="commit" type="submit" value="Save" />
</div>

In above, div.field is empty.

3条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-04-28 01:15

fields_for has new syntax.

= fields_for :plan, @plan do |builder| ...

in controller (action new) :

@plan = Parent.plans.new

read more here: http://api.rubyonrails.org/classes/ActionView/Helpers/FormHelper.html#method-i-fields_for

查看更多
乱世女痞
3楼-- · 2019-04-28 01:20

I stumbled across this from your rails issue, which appears to be not building the nested resource in your new action.

Are you calling build_material_asset in your controller? That could explain why the fields aren't getting rendered. If the nested object is nil, there are no object to render fields for.

Try something like this:

class MaterialsController < ApplicationController
  def new
    @material = Traditions::Material.new
    @material.build_material_asset
  end
end
查看更多
贼婆χ
4楼-- · 2019-04-28 01:26

I cannot check, but something like this?

- form_for @material, :html => {:class => 'form', :multipart => true} do |f|
    = errors_for @material

    #field
        = f.label :title
        = f.text_field :title

    #field
        = f.label :description
        = f.text_area :description, :rows => 5

    #field
        - f.fields_for :material_asset do |ma|
            = ma.label :asset
            = ma.file_field :asset

    .buttonrow
        = f.submit 'Save'

The problem is that you have nested =. You should use - for the outer iterations. Also, are you sure that .field works? Isn't it supposed to be #field?

查看更多
登录 后发表回答