关于多态关联的问题

时间:2010-12-16 11:30:22

标签: ruby-on-rails

现在我正在处理视频的缩略图文件。 我想使用多态关联:

class Picture < ActiveRecord::Base
  belongs_to :pictureable, :polymorphic => true
end


class Video < ActiveRecord::Base
  belongs_to :videoable, :polymorphic => true
  has_many :pictures, :as => :pictureable  # I want to use has_one :picture, :as => :picturealbe, it make sense to let each video have a single picture as thumbnail  but it doesn't work for me, video.picture return a nil
end

class Drummer < ActiveRecord::Base
  has_many :videos,:as => :videoable
  has_many :pictures, :as => :pictureable
end

我希望用它来显示带有缩略图的所有视频

<% @drummer.videos.each do |v|%>
<li>
<%= link_to video_path(v) do %>
<%= image_tag(v.pictures.find(1).url) %>
<h4><%= v.title %></h4>
<h5><%= v.desc %></h5>
<h6>event place</h6>
<% end %>
</li>
<% end %>

我在开发日志文件中遇到此错误:

ActionView::Template::Error (Couldn't find Picture with ID=1 [WHERE ("pictures".pictureable_id = 3 AND "pictures".pictureable_type = 'Video')]):
    92: <% @drummer.videos.each do |v|%>
    93: <li>
    94: <%= link_to video_path(v) do %>
    95: <%= image_tag(v.pictures.find(1).url) %>
    96: <h4><%= v.title %></h4>
    97: <h5><%= v.desc %></h5>
    98: <h6>event place</h6>
  app/views/drummers/show.html.erb:95:in `block (2 levels) in _app_views_drummers_show_html_erb___754323413_3886850_892596806'
  app/views/drummers/show.html.erb:94:in `block in _app_views_drummers_show_html_erb___754323413_3886850_892596806'
  app/views/drummers/show.html.erb:92:in 

`_app_views_drummers_show_html_erb ___ 754323413_3886850_892596806'

我的解决方案根本不优雅,但我无法想出更好的主意 有什么建议吗? 谢谢大家

2 个答案:

答案 0 :(得分:1)

我也是铁杆新手,但最近我遇到了类似的问题......这些问题对我有用:

class Video < ActiveRecord::Base
  belongs_to :videoable, :polymorphic => true
  has_one :picture, :foreign_key => :pictureable_id
end

希望这有帮助!

答案 1 :(得分:1)

您可以将图片标记呈现为

<%= image_tag(v.pictures.first.url) %>

当您明确说出v.pictures.find(1)时,它会尝试查找与给定视频相关联的图片并且ID为1,有时您在没有此类记录时会遇到错误。