我是RoR的新手。請告訴我如何從ActiveRecord :: Relation獲取屬性?比如我寫:RoR從ActiveRecord採取atrributes ::關係
@user = User.where(code: 123)
接下來我要帶屬性ID
id = @user.id
但這種方法是不行的。對不起,如果這個問題是愚蠢的。感謝早期
我是RoR的新手。請告訴我如何從ActiveRecord :: Relation獲取屬性?比如我寫:RoR從ActiveRecord採取atrributes ::關係
@user = User.where(code: 123)
接下來我要帶屬性ID
id = @user.id
但這種方法是不行的。對不起,如果這個問題是愚蠢的。感謝早期
當使用。凡它給你一個active record relation
所以你不能直接找到ID因爲它不是一個模型對象而是一個關係。
修復:
你可以做
@user = User.where(code: 123).first
OR
您可以使用dynamic finders
@user = User.find_by_code(123)
如果你想找到單個用戶與code == 123
,您可以使用find_by
方法,像這樣:
@user = User.find_by(code: 123)
它返回User
實例,所以你可以調用id
方法就可以了。
編輯:如果您使用的Rails之前4.x的版本,可以使用動態find_by_code
取景器:
@user = User.find_by_code(123)
您正在使用where
子句它返回數組。使用它像:
@user = User.where(code: 123).first
以上是不正確的查詢方式。所以,你也可以寫你的代碼,找出用戶喜歡:
@user = User.find_by_code(123)
通過以上兩種方式你會得到一個對象,你可以從中找到任何屬性。 @user.id
等
我猜你缺少first
,where
返回一個對象array
,所以你需要先用獲取對象從陣列的
做這個
@user = User.where(code: 123).first
id = @user.id
NoMethodError(未定義的方法' find_by'for#): –
2014-09-05 10:19:50
@VitaliyProdan - 你在運行什麼rails版本? – BroiSatse 2014-09-05 10:25:12