我的目标是使用标签创建一个系统,用于将照片与来自几个类(事件,组织,开发)中的任何一个的对象相关联。对于我的生活,我无法解决这个问题,尽管这似乎是一种非常普遍的情况。
除了最基本的Rails开发之外,我比较新,所以我很难形成这个问题。请原谅任何用词不当。
标记模型:
class Tag < ActiveRecord::Base
attr_accessible :photo_id, :taggable_id, :taggable_type
belongs_to :photo
belongs_to :taggable, :polymorphic => true
end
照片模特:
class Photo < ActiveRecord::Base
attr_accessible :tags_attributes
has_many :tags, :dependent => :destroy
accepts_nested_attributes_for :tags, :reject_if => lambda { |a| a[:taggable_id].blank? }
end
活动模式:
class Event < ActiveRecord::Base
has_many :tags, :as => :taggable, :dependent => :destroy
end
组织模式:
class Organization < ActiveRecord::Base
has_many :tags, :as => :taggable, :dependent => :destroy
end
开发模式:
class Development < ActiveRecord::Base
has_many :tags, :as => :taggable, :dependent => :destroy
end
在我的照片字段中,我正在尝试使用nested_form gem为照片添加标签(这样我以后可以在照片的视图中调用标记的对象,并在标记对象的视图中调用照片)
photos / new.html.erb(我已加入nested_form
javascript)
<% nested_form_for @photo, :html => { :multipart => true } do |f| %>
...
<%= f.fields_for :tags do |tag_form| %>
<%= tag_form.collection_select :taggable_id, Taggable.all, :id, :name %>
<%= tag_form.link_to_remove "remove" %>
<% end %>
<p><%= f.link_to_add "Add tag", :tags %></p>
...
<% f.submit "Add photo" %>
<% end %>
我的模特结构是否适合我想要做的事情?
,如果是的话,
如何以嵌套的形式正确指定he:taggable_id和:taggable_type?
提前感谢任何指导!
答案 0 :(得分:0)
您需要使您的Photo模型具有多态性,并使用attachment_fu / paperclip等内容上传照片。
class Photo < ActiveRecord::Base
has_attachment :content_type => :image,
:storage => :file_system,
:max_size => 2000.kilobytes,
:resize_to => '500x500>',
:thumbnails => { :thumb => '215x215>'}
validates_as_attachment
belongs_to :attachable, :polymorphic => true
end
class Event < ActiveRecord::Base
has_many :tags, :as => :taggable, :dependent => :destroy
has_many :attachments, :as => :attachable
end
class Organization < ActiveRecord::Base
has_many :tags, :as => :taggable, :dependent => :destroy
has_many :attachments, :as => :attachable
end
class Development < ActiveRecord::Base
has_many :tags, :as => :taggable, :dependent => :destroy
has_many :attachments, :as => :attachable
end
您的照片表应包含attachable_id和attachable_type列。有了这个,你应该能够将照片添加到所有存储在多态照片模型中的不同对象。标记也使用多态关联并以类似的方式工作。插件的文档会有所帮助。希望对你有用。