Използване на един модел за качване на снимки от няколко модела. Така наречената "polymorphic" асоциация.
Таблица за attachment_fu модел:
create_table :images do |t|
t.column :parent_id, :integer
t.column :content_type, :string
t.column :filename, :string
t.column :thumbnail, :string
t.column :size, :integer
t.column :width, :integer
t.column :height, :integer
t.column :user_id, :integer
t.column :asset_id, :integer
t.column :asset_type, :string
end
Магията започва тук :
t.column :asset_id, :integer
t.column :asset_type, :string
Модел за Attachment_fu: Image
class Image < ActiveRecord::Base
belongs_to :asset, :polymorphic => true, :dependent => :destroy
.....
Искаме да добавим снимка към друг модел:
class Link < ActiveRecord::Base
has_one :image, :class_name => 'Image', :as => :asset, :dependent => :destroy
....
Link контролер:
class LinksController < ApplicationController
def new
@link = Link.new
end
def create
@link = Link.new(params[:link])
if !params[:image][:uploaded_data].blank?
@image = Image.new(params[:image])
@link.image = @image
end
if @link.save
flash[:notice] = 'Линка е добавен успешно !'
redirect_to :action => 'list'
else
render :action => 'new'
end
end
def edit
@link = Link.find(params[:id])
@image = @link.image
end
def update
@link = Link.find(params[:id])
@link.attributes = params[:link]
if !params[:image][:uploaded_data].blank?
@image = Image.new(params[:image])
@link.image = @image
end
if @link.update_attributes(params[:link])
flash[:notice] = 'Линка беше променен !'
redirect_to :action => 'list'
else
render :action => 'edit'
end
end