2014-01-08 136 views
0

我在Rails控制器2個實例變量:設置隨機Rails變量不等於另一個隨機變量?

@stories = Post.tagged_with("test").all(:order => "RANDOM()", :limit => 1) 
@stories2 = Post.tagged_with("test").where('post_id not in (?)', [@stories]).all(:order => "RANDOM()", :limit => 1) 

我不想讓其他的實例變量平起平坐,但他們都必須是「隨機」(我知道這在技術上是不是隨機的)。是否可以設置一個除一個值之外的隨機變量?

回答

2
@stories, @stories2 = Post.tagged_with("test").all(order: "RANDOM()", limit: 2) 
+3

這比我的回答要好。 –

+0

這是很酷...並完美的作品:) – sameera207

+0

爲@MikeTrpcic +1,讚賞更好的答案:) – sameera207

1

你可以使所述第二查詢返回2,並做一些邏輯來檢查等價

@stories = Post.tagged_with("test").all(:order => "RANDOM()", :limit => 1) 
@stories2 = Post.tagged_with("test").where('post_id not in (?)', [@stories]).all(:order => "RANDOM()", :limit => 1) 

@stories2.delete_at(@stories[0] == @stories2[0] ? 0 : 1); 

與上面的代碼中,如果來自所述第一對象的單個元件是相同的,第二的,我們刪除它並使用其他。如果它們不相同,我們刪除第二個數組中的「額外」故事。最後,每個實例變量將在數組中有一個項目,並且它們不會相同。