且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Rails 得到一个没有循环的记录

更新时间:2023-11-14 21:58:28

<%= image_tag(@asset.attachments.find_by_main_image(true).attachment.s_640_480) %>

将这段代码放在您的视图中不太好,因此我建议将其放在您的资产模型的实例方法中:

It's not so nice to have this code in your view, so I'd recommend to put it in an instance method of your asset model:

class Asset < ActiveRecord::Base
  has_many :attachments

  def main_image 
    attachments.find_by_main_image(true).attachment.s_640_480
  end
end

然后在你看来你可以这样做:

Then in your view you can do:

<%= image_tag(@asset.main_image) %>

您可能需要添加一些检查对象是否为空.祝你好运.

You probably have to add some checks that objects are not nil. Good luck.