Rails Невозможно сохранить вложенный атрибут внука, используя update_attrib

Я работаю над системой загрузки скрепок, где у меня есть пользователь, у которого много загрузок, которые, в свою очередь, имеют много отношений Upload_Images.

Из-за особенностей работы моей системы, пользователь создается один раз, а затем в него добавляются закачки, и необходимо создать записи закачки в действии обновления контроллеров пользователя. Первоначально нужно было создать только запись о загрузке, но мне пришлось расширить функциональность, чтобы включить в нее Upload_image. В существующем состоянии создается запись о загрузке, но не файл upload_image.

Он является хэшем params для того, где вызывается метод Update после отправки формы New upload (с изображением загрузки).

"_method"=>"put",
 "authenticity_token"=>"fEDOZfJ6UarMD/nNM7t86zYXrEkTFtXyrXKJglYZ0Jw=",
 "user"=>{"uploads_attributes"=>{"0"=>{"id"=>"37"},
 "1"=>{"id"=>"36"},
 "2"=>{"id"=>"35"},
 "3"=>{"id"=>"34"},
 "4"=>{"id"=>"33"},
 "5"=>{"id"=>"32"},
 "6"=>{"id"=>"31"},
 "7"=>{"id"=>"30"},
 "8"=>{"id"=>"29"},
 "9"=>{"id"=>"28"},
 "10"=>{"id"=>"27"},
 "11"=>{"id"=>"26"},
 "12"=>{"id"=>"25"},
 "13"=>{"id"=>"24"},
 "14"=>{"id"=>"23"},
 "15"=>{"id"=>"22"},
 "16"=>{"id"=>"21"},
 "17"=>{"id"=>"20"},
 "18"=>{"id"=>"19"},
 "19"=>{"id"=>"18"},
 "20"=>{"id"=>"17"},
 "21"=>{"id"=>"16"},
 "22"=>{"id"=>"15"},
 "23"=>{"id"=>"14"},
 "24"=>{"id"=>"13"},
 "25"=>{"id"=>"12"},
 "26"=>{"id"=>"11"},
 "27"=>{"id"=>"10"},
 "28"=>{"upload"=>#<ActionDispatch::Http::UploadedFile:0x00000004103d18 @original_filename="robot.rres",
 @content_type="application/octet-stream",
 @headers="Content-Disposition: form-data; name=\"user[uploads_attributes][28][upload]\"; filename=\"robot.rres\"\r\nContent-Type: application/octet-stream\r\n",
 @tempfile=#<File:/tmp/RackMultipart20120505-2595-lmr2j4>>,
 "name"=>"Test",
 "file_description"=>"Test",
 "private"=>"0",
 "file_category"=>"1",
 "upload_images_attributes"=>{"0"=>{"upload_image"=>#<ActionDispatch::Http::UploadedFile:0x00000004103a98 @original_filename="Low_Res_NAO_NextGen_04.png",
 @content_type="image/png",
 @headers="Content-Disposition: form-data; name=\"user[uploads_attributes][28][upload_images_attributes][0][upload_image]\"; filename=\"Low_Res_NAO_NextGen_04.png\"\r\nContent-Type: image/png\r\n",
 @tempfile=#<File:/tmp/RackMultipart20120505-2595-16gf0jl>>,
 "preview"=>"0"}}}},
 "username"=>"chunter"},
 "commit"=>"Submit Upload",
 "id"=>"chunter"}

Как видите, параметры как для файла выгрузки, так и для файла Upload_Image отправляются, но только выгрузка сохраняется в базу данных.

Мой метод обновления:

  def update
    @user = User.find_by_username(params[:id])
    #Update the users uploadS
    unless @user.update_attributes(params[:user])
      session[:error] = @user.errors.full_messages

      #render :action => "show"
      respond_to do |format|
        format.html { redirect_to :back, notice: 'Update unsuccessful.' }
        format.json { head :ok }
      end
    else
      respond_to do |format|
        format.html { redirect_to :back, notice: 'Update successful.' }
        format.json { head :ok }
      end
    end    
  end

Вот мои модели (я убрал лишние вещи для удобства чтения):

пользователь

class User < ActiveRecord::Base

  attr_accessible :email, :password, :password_confirmation, :remember_me, :admin, :username, :avatar, :description, :name, :country, :province, :gender, :occupation, :city, :address, :birth_date, :uploads_attributes, :avatar_attachment_size, :avatar_file_type, :banned_until, :upload_images_attributes
  has_many :posts, :dependent => :destroy, :order => 'created_at desc'
  has_many :topics, :dependent => :destroy, :order => 'created_at desc'
  has_many :viewings, :dependent => :destroy, :order => 'updated_at desc'
  has_many :uploads, :dependent => :destroy, :order => 'created_at desc'
  has_many :news, :dependent => :destroy, :order => 'created_at desc'
  has_many :events, :dependent => :destroy, :order => 'date desc'
  has_many :blog_entries, :foreign_key => :user_id
  has_many :registers
  has_many :members
  has_many :teams, :through => :members

  accepts_nested_attributes_for :uploads, :allow_destroy => true
  has_attached_file :avatar, :styles => {:thumb=> "70x70#", :small  => "150x150>" }, :default_url => "/images/missing.jpg"


end

Загрузить

  class Upload < ActiveRecord::Base
    include ActiveModel::Validations

    belongs_to :user
  belongs_to :upload_category, :foreign_key => :file_category  
  has_many :upload_images, :dependent => :destroy  
  accepts_nested_attributes_for :upload_images, :reject_if => lambda { |t| t[':upload_images'].nil? }
    has_attached_file :upload,  :path => ":rails_root/:class/:id/:basename.:extension", :url => ":rails_root/:class  /:id/:basename.:extension"

    attr_accessible :file_category, :file_description, :user_id, :upload, :name, :private, :uploads, :upload_images_attributes

    validates_attachment_size :upload, :less_than => 30.megabyte
    validates_presence_of :upload_file_name, :message => "must contain a valid file."
    validates :name, :presence => true
  validates :name, :length => { :maximum => 30 }

    validates_with FileValidator
end

Загрузить изображения

class UploadImage < ActiveRecord::Base

belongs_to :upload
has_attached_file :image, :styles => { :small => "150x150>", :large => "320x240>"}, :default_url => "/images/missing.jpg"  


end

редактировать

Если я достану

 :reject_if => lambda { |t| t[':upload_images'].nil? }

в моей модели загрузок я получаю неизвестный атрибут: ошибка upload_image в моем контроллере пользователей при попытке обновления.

1 ответ

Решение

Было 2 проблемы, которые препятствовали сохранению моего Upload_Image.

  1. Следующая строка в моей модели upload_image:reject_if => lambda { |t| т [':'] upload_images ноль.? } моя персистентность потерпела неудачу молча, потому что в загрузке файла были нулевые значения, которые я пытался сохранить.
  2. Я получал неизвестный атрибут:upload_image, потому что, на мой взгляд, у меня было file_field:upload_image, но в моей модели я называю вложение изображения как:image. Это вызвало запуск reject_if lamba в моей модели
Другие вопросы по тегам