7

我想与回形针建立多态关联,并允许我的用户拥有一个头像和多个图像。

附件型号:

class Attachment < ActiveRecord::Base
belongs_to :attachable, :polymorphic => true
end

class Avatar < Attachment
has_attached_file :image, :styles => { :thumb => "150x150>", :view => "260x180>" },
end

class Image < Attachment
has_attached_file :image, :styles => { :thumb => "150x150>", :view => "260x180>" },
end

用户模型:

has_one :avatar, :as => :attachable, :class_name => 'Attachment', :conditions => {:type => 'avatar'}
accepts_nested_attributes_for :avatar

用户控制器:

def edit
   @user.build_avatar
end

用户查看表单:

<%= form_for @user, :html => { :multipart => true } do |f| %>

  <%= f.fields_for :avatar do |asset| %>
      <% if asset.object.new_record? %>
          <%= asset.file_field :image %>
      <% end %>
  <% end %>

当我尝试保存更改时,我收到错误 => 未知属性:头像

如果我在 has_one 关联中删除 :class_name => 'attachment' 我得到错误 => 未初始化的常量 User::Avatar

我还需要将头像附加到博客文章,所以我需要关联是多态的(或者至少我认为是这样)

我很难过,任何帮助将不胜感激。

4

2 回答 2

7

我确实有一个项目正在成功使用回形针和多态关联。让我告诉你我有什么,也许你可以将它应用到你的项目中:

class Song < ActiveRecord::Base
  ...
  has_one :artwork, :as => :artable, :dependent => :destroy
  accepts_nested_attributes_for :artwork
  ...
end

class Album < ActiveRecord::Base
  ...
  has_one :artwork, :as => :artable, :dependent => :destroy
  accepts_nested_attributes_for :artwork
  ...
end

class Artwork < ActiveRecord::Base
  belongs_to :artable, :polymorphic => true
  attr_accessible :artwork_content_type, :artwork_file_name, :artwork_file_size, :artwork

  # Paperclip
  has_attached_file :artwork,
    :styles => {
      :small => "100",
      :full => "400"
    }

  validates_attachment_content_type :artwork, :content_type => 'image/jpeg'
end

歌曲表格和专辑表格包括以下部分:

<div class="field">
<%= f.fields_for :artwork do |artwork_fields| %>
  <%= artwork_fields.label :artwork %><br />
  <%= artwork_fields.file_field :artwork %>
<% end %>

不要忘记在表单中包含 :html => { :multipart => true }

艺术品控制器.rb

class ArtworksController < ApplicationController
  def create
    @artwork = Artwork.new(params[:artwork])

    if @artwork.save
        redirect_to @artwork.artable, notice: 'Artwork was successfully created.'
    else
        redirect_to @artwork.artable, notice: 'An error ocurred.'
    end
  end
end

最后,摘自 song_controller.rb:

def new
    @song = Song.new
    @song.build_artwork
end
于 2012-05-16T18:24:29.577 回答
0

我不确定你真的需要多态。这种使用 has_many :through 的方法怎么样?通俗的说,用户有一个头像,里面有多张图片,通过这个关联,你可以调用 User.images 来获取与头像关联的图片集合。

http://guides.rubyonrails.org/association_basics.html

class User < ActiveRecord::Base
  has_one :avatar
  has_many :images, :through => :avatar
end

class Avatar < ActiveRecord::Base
  belongs_to :user
  has_many :images
end

class Image < ActiveRecord::Base
  belongs_to :avatar
  has_attached_file :image, :styles => { :thumb => "150x150>", :view => "260x180>" },
end

说了这么多,我想知道为什么无论如何你都需要经历这一切。为什么不只是做

class User < ActiveRecord::Base
  has_many :avatars
end

这将为您提供任意数量的图像(化身)。

于 2012-05-15T20:17:51.280 回答