问题
Suppose I have an model:
class Post
end
posts = Post.where(***)
puts posts.class # => ActiveRecord::Relation
Then how can I get the model class name through the variable 'posts', maybe some method called model_class_name:
puts posts.model_class_name # => Post
Thanks :)
回答1:
The #klass attribute of ActiveRecord::Relation returns the model class upon which the relation was built:
arel = User.where(name: "fred")
arel.klass # User
To get the class's name:
arel.klass.name
Tested in ActiveRecord 4.2.4
回答2:
For a solution that works, even if there are no related items:
class Post < ActiveRecord::Base
has_many :comments
end
Post.reflect_on_association(:comments).klass
=> Comment
回答3:
The most simple and direct answer to your question is:
posts.first.class.name
Which is equivalent to writing:
posts.[0].class.name
You can do this because your query will return an enumerable result. (ActiveRecord::Relation implements Ruby's Enumerable interface).
-- Scott
来源:https://stackoverflow.com/questions/4263844/in-rubyonrails-how-to-get-the-associated-model-class-from-and-activerecordrel