助手“fields_for”无效

时间:2011-05-22 04:47:56

标签: ruby-on-rails ruby-on-rails-3 haml helpers ruby-on-rails-3.1

我正在使用嵌套属性,但我的视图中未加载这些字段。 有人知道我错过了什么吗?

Rails 3.1,Ruby 1.9.2

模型1:

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

模型2:

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

查看(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'

结果HTML(部分):

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

在上面,div.field为空。

3 个答案:

答案 0 :(得分:11)

我偶然发现了您的rails issue,这似乎没有在您的new操作中构建嵌套资源。

您是否在控制器中呼叫build_material_asset?这可以解释为什么字段没有被渲染。如果嵌套对象为nil,则没有对象呈现字段。

尝试这样的事情:

class MaterialsController < ApplicationController
  def new
    @material = Traditions::Material.new
    @material.build_material_asset
  end
end

答案 1 :(得分:3)

fields_for有新的语法。

= fields_for :plan, @plan do |builder| ...
控制器中的

(动作新):

@plan = Parent.plans.new

在此处阅读更多内容:http://api.rubyonrails.org/classes/ActionView/Helpers/FormHelper.html#method-i-fields_for

答案 2 :(得分:0)

我无法检查,但这样的事情?

- 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'

问题是您嵌套了=。您应该使用-进行外部迭代。此外,您确定.field有效吗?它不应该是#field吗?