2011-07-27 35 views
2

我有一个模型,每个资产都有一个main_image,而在附件模型中,每个资产只能有一个真值。我想知道是否有一种方法来拉这个记录没有循环通过每个记录,看看main_image设置为true或false。Rails得到一个没有循环的记录

澄清:

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

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

,但是,我想知道如何做到这一点没有环...... 我不知道如何澄清任何更多...但这样的:

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

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

+0

我想我差不多明白的问题,但你可以张贴一些简单的代码示例,所以我们会确定吗? – Arsen7

+0

你能澄清你的问题吗?目前,我无法理解,你有什么设置和你想要什么。 – rubish

+0

@ Arsen7 Gupta我试图澄清,不好意思,如果它仍然令人困惑。 –

回答

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

这不是那么高兴有这样的代码在你的看法,所以我建议你把它放在你的资产模型的实例方法:

class Asset < ActiveRecord::Base 
    has_many :attachments 

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

然后在您的视图,你可以做:

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

您可能必须添加一些检查,对象不是零。祝你好运。

+0

现在就进行验证,谢谢! –

0

如果我明白你需要在数据库中找到一些条目,如果它的值是真或假的权利?

因此,您需要在您的模型中创建一个方法或在控制器中使用带条件的查找,您可以在the documentation内找到所需的全部内容。

1

你可以加入它,就像这样:

class Asset < ActiveRecord::Base 
    has_many :attachments do 
     def main_image 
      where(:main_image => true).first 
     end 
    end 
end 

使用您的看法,像这样:

<%= image_tag @asset.attachments.main_image.s640_480 %>