2011-07-27 28 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 %>