accepted_nested_attributes_for与formtastic和paperclip结合使用

时间:2010-10-29 16:27:45

标签: activerecord ruby-on-rails-3 paperclip formtastic nested-attributes

我正在尝试我有一个简单的一对多关联。我试图通过嵌套表单更新属于相册的照片:

相册的编辑表格:

<%= semantic_form_for(@album, :url => user_album_path(@user, @album), :html => {:method => :put} ) do |f| %>
 <%= f.inputs do %>
  <%= f.input :title %>
  <%= f.input :description %>
 <% end %>
 <%= f.inputs :for => :photos do |builder|%>
  <%= builder.input :_destroy, :as => :boolean %>
 <% end %>
 <%= f.submit "Submit", :disabled_with => 'Submiting...' %>
<% end %>

它有效并且不能同时工作。显然标题和描述没有问题,并且formtastic正确地为相册中的每张照片制作一个复选框。但在这里,我已经有了第一个问题:

1)如何在复选框旁边显示照片? 我设法解决了这个问题:

<%= image_tag(builder.object.image.url(:album)) %>

显示图像。

这里有专辑和专辑模型:

class Album < ActiveRecord::Base

  belongs_to          :user
  has_many            :photos, :dependent => :destroy

  #attr_accessible     :title, :description 

  validates_presence_of :title, :description

  accepts_nested_attributes_for :photos, :allow_destroy => true
end

照片模型:

class Photo < ActiveRecord::Base
  belongs_to        :user
  belongs_to        :album

  has_attached_file :image, :styles => { :original => ["441x800>", :png], 
                                         :album => ["140x140#", :png], 
                                         :tiny => ["16x16#", :png] }

  validates_attachment_presence :image
  validates_attachment_content_type :image, :content_type => ["image/jpeg", "image/png", "image/gif"]
 end

专辑控制器:

def update
    @user = User.find(params[:user_id])
    @album = @user.albums.find(params[:id])
    if @album.update_attributes(params[:album][:photos_attributes])
      flash[:success] = t('users.flash.album_updated')
      redirect_to @user
    else
      render :edit
    end
end

抛出错误:

ActiveRecord::UnknownAttributeError in AlbumsController#update

unknown attribute: 0
Rails.root: /Users/stefanohug/orangerie

Application Trace | Framework Trace | Full Trace
app/controllers/albums_controller.rb:50:in `update'
Request

Parameters:

{"_snowman"=>"☃",
 "_method"=>"put",
 "authenticity_token"=>"bE4AidmbaVoG9XBqolCxheyWtd7qeltkIpMRgd8c4Fw=",
 "album"=>{"title"=>"lol",
 "description"=>"hihi",
 "photos_attributes"=>{"0"=>{"_destroy"=>"1",
 "id"=>"72"},
 "1"=>{"_destroy"=>"1",
 "id"=>"73"},

第50行对应于update_attributes行。

感谢您的帮助。

燕姿

1 个答案:

答案 0 :(得分:3)

我发现了错误。它在控制器中:

@album.update_attributes(params[:album][:photos_attributes])

应为:

@album.update_attributes(params[:album])

Duh ......:D