Should model methods always return models of their own type?
For model methods that return models or collections of model开发者_StackOverflow社区s, should these methods return only models of type corresponding to the class they live in?
For instance, if I have a Theater model, should its methods always return models of type Theater, or would it ever make sense to return models of type Showtime (eg. Theater.get_showtimes(theater_id) vs. Showtimes.get_by_theater_id(theater_id)).
I asked myself this question just about every time I run into situations just like yours. I personally try to stick to a model returning its own type. So in that situation I'd go with Showtimes.get_by_theater_id(theater_id)
. It just makes more sense when I look at the code later.
If your Theater
has_many
Showtimes
, then you could access it by Theater.Showtimes
.
A couple of more ActiveRecord-style ways of implementing your example (Theater.get_showtimes(theater_id)
) would be:
Theater.find(theater_id).showtimes
instead. This assumes you've used ActiveRecord associations as zsalzbank mentions.Showtimes.find_by_theater_id(theater_id)
I'd suggest you use the power of ActiveRecord for what it does best, and not worry about artificially restricting yourself to what class methods may return.
Now, if we're talking purely theory, I'd argue for following the conventions of the language and/or framework you're using.
Looking at ActiveRecord::Base
(http://apidock.com/rails/ActiveRecord/Base) it is trivial to find a bunch of class methods that return something not ActiveRecord::Base
. For example, ActiveRecord::Base.connection
returns a subclass of ActiveRecord::ConnectionAdapters::AbstractAdapter
and ActiveRecord::Base.table_name
returns a String
. Obviously, your model has those methods as well, thus it returns those values.
I don't see any benefit to putting the proposed restriction on yourself/your code - especially since you've already broken the rule by inheriting from ActiveRecord::Base
and will have to deal with different return classes anyways.
Short answer: no.
A model is simply a ruby class file that represents some table in a database and is really only used in the ruby-on-rails world. A model doesn't return anything, it's just a container. A model has methods/functions that return data and by no means do they have to return only the same model object.
For example (pseudo code):
class Dog < AR:B
def hack_the_world
//do hacking and return array of passwords
//...
end
end
We have a Dog model here. For example we get these methods from rails which return Dog objects:
dogs=Dog.all
dog=Dog.find(1)
dog=Dog.where(:name => 'fido')
But then we can call our method that doesn't return any Dog objects
passwords=Dog.new.hack_the_world
精彩评论