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.
Clarification:
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:
<%= ima开发者_开发百科ge_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.
You can join it up like so:
class Asset < ActiveRecord::Base
has_many :attachments do
def main_image
where(:main_image => true).first
end
end
end
Use in your views like so:
<%= image_tag @asset.attachments.main_image.s640_480 %>
If i understant you need to find some entries in database if the value of it is true or false right ?
So you need to make a method inside your model or use a find with condition in the controller, you can find all what you want inside the documentation.
精彩评论