ruby 使用多态数据库模型自动创建Active Record关联:http://api.rubyonrails.org/classes/ActiveRecord/Associat

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ruby 使用多态数据库模型自动创建Active Record关联:http://api.rubyonrails.org/classes/ActiveRecord/Associat相关的知识,希望对你有一定的参考价值。

class Picture < ActiveRecord::Base
  belongs_to :imageable, :polymorphic => true
  attr_accessible :imageable_id, :imageable_type, :name, :url
end

class Document < ActiveRecord::Base
  has_many :pictures, :as => :imageable
  attr_accessible :title, :content
end

class User < ActiveRecord::Base
  has_many :pictures, :as => :imageable
  attr_accessible :name, :email, :superpower
end

@document = Document.new({ :title => 'New Document', :content => 'Lorem ipsum' })

# download file, save reponse as @photo

@document.build_picture({ :name => 'Kitty', :url => @photo.path })

@document.save

以上是关于ruby 使用多态数据库模型自动创建Active Record关联:http://api.rubyonrails.org/classes/ActiveRecord/Associat的主要内容,如果未能解决你的问题,请参考以下文章