ruby-on-rails – 帮助者“fields_for”无效

前端之家收集整理的这篇文章主要介绍了ruby-on-rails – 帮助者“fields_for”无效前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在使用嵌套属性,但我的视图中没有加载字段.
有人知道我错过了什么吗?

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是空的.

解决方法

我偶然发现了你的 rails issue,这似乎没有在你的新动作中构建嵌套资源.

你在控制器中调用build_material_asset吗?这可以解释为什么字段没有被渲染.如果嵌套对象为nil,则没有对象呈现字段.

尝试这样的事情:

class MaterialsController < ApplicationController
  def new
    @material = Traditions::Material.new
    @material.build_material_asset
  end
end
原文链接:https://www.f2er.com/ruby/267478.html

猜你在找的Ruby相关文章