假設我有一個模型:在rubyonrails中,如何從ActiveRecord :: Relation對象獲取關聯的模型類?
class Post
end
posts = Post.where(***)
puts posts.class # => ActiveRecord::Relation
然後,我如何能夠通過可變「帖子」,也許有些方法叫做model_class_name獲取模型類名:
提出posts.model_class_name#=>郵政
謝謝:)
假設我有一個模型:在rubyonrails中,如何從ActiveRecord :: Relation對象獲取關聯的模型類?
class Post
end
posts = Post.where(***)
puts posts.class # => ActiveRecord::Relation
然後,我如何能夠通過可變「帖子」,也許有些方法叫做model_class_name獲取模型類名:
提出posts.model_class_name#=>郵政
謝謝:)
最簡單,最直接的回答你的問題是:
posts.first.class.name
即相當於寫作:
posts.[0].class.name
你可以做到這一點,因爲你的查詢將返回可枚舉結果。 (ActiveRecord :: Relation實現了Ruby的Enumerable接口)。
- 斯科特
的ActiveRecord::Relation的#klass屬性返回賴以關係是建立模型類:
arel = User.where(name: "fred")
arel.klass # User
要獲取類的名字:
arel.klass.name
測試中ActiveRecord 4.2.4
Hey Croplio,4個月過去了。這個答案解決了你的問題嗎? – Scott 2011-04-03 00:02:13