Rails嵌套表单使用accepts_nested_attributes_for

时间:2012-04-12 08:35:57

标签: nested-forms ruby-on-rails-3.2

我正在关注此rails cast以创建嵌套表单: http://railscasts.com/episodes/196-nested-model-form-part-1

我有一个'word'模型,它有一个图像,当更新单词我也想更新图像。我正在使用rails 3.2.3。

我的问题是图片表单没有显示在页面上。

word.rb:

class Word < ActiveRecord::Base

  attr_accessible :name
  validates_presence_of :name

  belongs_to :category
  attr_accessible :category_id

  has_one :image
  accepts_nested_attributes_for :image, :allow_destroy => true
  attr_accessible :image_attributes

end

字/ _form.html.erb:

<%= form_for @word, :html => {:multipart => true} do |f| %>
    <% if @word.errors.any? %>
        <div id="error_explanation">
          <h2><%= pluralize(@word.errors.count, "error") %> prohibited this word from being saved:</h2>

          <ul>
            <% @word.errors.full_messages.each do |msg| %>
                <li><%= msg %></li>
            <% end %>
          </ul>
        </div>
    <% end %>

    <div class="field">
      <%= f.label :category %>
      <br/>
      <%= f.collection_select(:category_id, Category.all, :id, :name) %>
      <br/>
      <%= f.label :name %>
      <br/>
      <%= f.text_field :name %>
      <br/>
      <%= image_tag @word.image.file_url(:thumb).to_s unless @word.image.nil? %>
      <%= f.fields_for :image do |builder| %>
          <br/>
          <%= builder.label :file, "Image" %>  <br/>
          <%= builder.file_field :file %>
          <%= builder.hidden_field :file_cache %>
      <% end %>
    </div>
    <div class="actions">
      <%= f.submit %>
    </div>
<% end %>

非常感谢任何帮助,干杯!

1 个答案:

答案 0 :(得分:0)

通过删除旧的“word”条目并添加

解决了问题
@word.build_image

到words_controller中的'new'动作。

相关问题