Rails 得到一个没有循环的记录 [英] Rails get one record without loop

查看:30
本文介绍了Rails 得到一个没有循环的记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个模型,每个资产都有一个 main_image,在附件模型中,每个资产只能有一个真实值.我想知道是否有一种方法可以在不遍历每个记录的情况下提取此记录以查看 main_image 是设置为 true 还是 false.

I have a model that has a main_image per asset and in the attachment model this can only have one true value per asset. I am wondering if there is a way to pull this record without looping through every record to see if main_image is set to true or false.

说明:

我可以使用以下代码找到该值:

I can find the value by using the following code:

<% @asset.attachments.each_with_index do |attachment, i| %>
    <%= image_tag(attachment.attachment.s_640_480) if !attachment.main_image.nil? && attachment.main_image%>
<%end%>

但是,我想知道如何在没有循环的情况下做到这一点......我不知道如何进一步澄清......但类似:

but, I am wondering how to do this without a loop... I don't know how to clarify any more...but something like:

 <%= image_tag(@attachment.where_main_image.s_640_480) %> 

我知道这行不通,但基本上就是这个概念

I know that won't work but basically that is the concept

推荐答案

<%= 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.

这篇关于Rails 得到一个没有循环的记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆