2015-05-26 36 views
0

我想從users獲得channel作爲字符串,其中id是隨機的。但我有一些問題。 代碼:ActiveRecord .select .where

2.2.1 :001 > User.select(:id, :channel).where(:id => rand(1..User.count)) 
    (0.2ms) SELECT COUNT(*) FROM `users` 
    User Load (0.3ms) SELECT `users`.`channel` FROM `users` WHERE `users`.`id` = 1 
=> #<ActiveRecord::Relation [#<User id: 1, channel: "Nickname">]> 

當我想要顯示它:

#<User::ActiveRecord_Relation:0x0000000a196388> 

但我只是想顯示 「暱稱」。 請幫忙。

回答

2

您需要使用那麼#first方法,如:

User.select(:id, :channel) 
    .where(:id => rand(1..User.count)) 
    .first.channel 

閱讀select文檔來了解它是如何工作的。