मैं चयन करने के लिए कोशिश कर रहा था एक विशेषता के आधार पर uniq वस्तुओं का उपयोग करते हुए @videos.uniq{|p| p.author}
रेल: सरणी के लिए activerecord संबंध मोड़ने का सही तरीका?
time = Time.new(2014, 12)
start_time = time.beginning_of_month
end_time = time.end_of_month
videos = Video.where("created_at > ? AND created_at < ?", start_time, end_time).where("likes > ?", 15)
selected_videos = videos.uniq{|p| p.author}
puts videos.count, videos.class, selected_videos.count
#=> 23, Video::ActiveRecord_Relation, 23
videos_first = videos.first(23)
selected_videos = videos_first.uniq{|p| p.author}
puts videos_first.count, videos_first.class, selected_videos.count
#=> 23, array, 10
.uniq
ActiveRecord_Relation
के लिए नहीं है। और समस्या यह है कि क्वेरी Video::ActiveRecord_Relation
लौटाती है, लेकिन मुझे array
की आवश्यकता है।
निश्चित रूप से, यह to_a
का उपयोग कर हासिल किया जा सकता है, लेकिन यह सुरुचिपूर्ण है?
- इसे संभालने का सही तरीका क्या है?
activerecord:relation
के लिए उपयोग करना संभव है?
'to_a' * किसी भी * को सरणी में बदलने का सही तरीका है। – meagar
एन + 1 क्वेरी के बारे में सावधान रहें। 'Video.where (...) का उपयोग करके आपके पास एक और अधिक कुशल क्वेरी होगी। {to_a.uniq {| p | को कॉल करने से पहले '(लेखक)' शामिल है। p.author} ' –