【发布时间】:2013-12-12 08:22:41
【问题描述】:
我一直在使用paperclip,模型为user has_many :images 和image belongs_to:user。现在我想让多态性为图像模型工作,这样用户,post 有很多图像和@ 987654324@.我正在努力,但我不自信,因为我不清楚回形针的概念。现在这些是我所做的更改,但我需要做哪些进一步的更改才能获得user has many images 的关联和images belongs to imageable ,polymorphic =>true.Below 是我所做的,但没有得到任何结果。任何帮助将不胜感激......。我只需要图像的多态性,例如用户有很多图像,帖子有很多图像.....等其中图像属于可成像,:多态=真。
image.rb
belongs_to :imageable,:polymorphic=>true
has_attached_file :avatar, :url => "/assets/images/#{imageable_type}/#{imageable_id}/:style/:basename.:extension",
:path => ":rails_root/public/assets/images/#{imageable_type}/#{imageable_id}/:style/:basename.:extension", :default_url => 'dashboard/default_avatar.jp
g'
user.rb
has many:images ,:as=>imageable,:dependent=>destroy
将文件迁移到图像
class CreateImages < ActiveRecord::Migration
def change
create_table :images do |t|
t.string :name
t.references :site
t.string :image_file_name, :null => true
t.string :image_content_type, :null => true
t.integer :image_file_size, :null => true
t.timestamps
end
end
end
为 user.rb 迁移
class CreateUsers < ActiveRecord::Migration
def change
create_table(:users) do |t|
t.string :first_name
t.string :last_name
t.string :username
t.string :mobile_number
t.string :email
t.references :image
t.timestamps
end
我将允许用户上传图片或编辑图片的视图表单
profile.html.erb.....使用remotipart gem
<%= form_for(@user,:url=>'add_image_to_user_path',:html => {:multipart => true},:remote=>true) do |f |%>
<%= f.file_field :images, :multiple => true %>
<%= f.submit "Add image" %>
<%end%>
users_controller.rb
##now how i should update the users image who has already logged in
##i tried @user.update_attribute(params[:user]) but i cannot see any update query in the log
- ##i can only see --->paperclip saving attachment
def add_image_to_user
@user=User.new
end
【问题讨论】:
标签: ruby-on-rails ruby-on-rails-3 polymorphism paperclip