根据某些条件获取载波图像?

时间:2012-09-07 21:12:41

标签: ruby-on-rails ruby-on-rails-3 carrierwave

如何获得具有一定条件的载波图像?

例如:

  image_tag @profile.photos.first.file_url(:profile)

返回第一张图片,但如果我想要像

那样的话
@photo = Photo.where(:attachable_id => 1, :attachable_type => "Profile", :main => true)

:main => true表示这是用户选择的个人资料图片。

另请注意,

我有这个功能,这是一团糟:

def show_avatar_thumb(id)
    @profile = User.find(id).profile rescue nil
    image_tag @profile.photos.first.file_url(:img_96x96)
  rescue
    image_tag ("/assets/avatars/img_96x96.png")
  end

有没有办法改善这个? THX!

1 个答案:

答案 0 :(得分:1)

def show_avatar_thumb(id)
  begin
    user = User.find(id)
  rescue ActiveRecord::RecordNotFound
    image_tag ("/assets/avatars/img_96x96.png")
  else
    image_tag user.profile.photos.where(main: true).first.file_url(:img_96x96)
  end
end

我会把where(main: true)拉出来并把它放在模型范围内。

相关问题