开发者

question about polymorphic association

Now I'm dealing with the video's thumbnail file. I want to use a polymorphic association:

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

and I want to use this to display all the video with it's thumbnail

<% @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 %>

I got this error in the development log file:

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/开发者_Python百科show.html.erb:92:in 

`_app_views_drummers_show_html_erb___754323413_3886850_892596806'

my solution is not elegant at all, But I can't come up with a better idea any suggestion? thanks everyone


You can render the image tag as

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

When you explicitly say v.pictures.find(1) it will try to find the picture which is associated with the given video and has ID 1 and sometimes you stuck with the error when no such record exists.


I'm also a rails newbie, but I had a similar problem recently... Something along these lines worked for me:

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

Hope this helps!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜