Sorry for the small question.
Suppose you have the following getter:
defusers
@users||=User.where (foo:bar)
end
The above problem is associated with an array of models from the name users, but
It is actually to return ActiveRecord::Relation
.
So I thought it would be better to use the following name.
def user_relationship
@user_relationship||=User.where(foo:bar)
end
Which do you think is more appropriate?
ruby-on-rails
There are a lot of strange things.
defusers
@users||=User.where (foo:bar)
end
This code is recognized as "Return ActiveRecord::Relationship" code.Therefore, there is no point in making a note.
defusers
User.where (foo:bar)
end
A method of defining search criteria is scope
.
scope:users->{where(foo:bar)}
It is obvious that this transformation will return ActiveRecord::Relationship in terms of code, so it is not associated with an array of models from the name of users.Even if it's scaffold,
@users=User.all
A code like this is generated, but @users is also ActiveRecord::Relation
(Most Rails show "arrangement of models" is a bad sign.)
Now,
scope:users->{where(foo:bar)}
This is a method of defining search criteria in advance, but I have no idea what the search criteria are, whether the name is users
or users_relationship
.
Therefore, I thought that I am not familiar with Rails-like code, which may be the cause of the discomfort.
In the first place, it is difficult to apply the rule "Methods with only plural names always return an array" to Rails.Methods that Rails automatically generates do not always return arrays with multiple names only.Rather, methods that return models based on information retrieved from the database often return ActiveRecord::Relation
(or its subclass).For example, if User
is set to has_many:users
for one-to-many associations, the return value of the users
method is User::ActiveRecord_Associations_Collection/Code>, a subclass of
ActiveRecord
.This is not an array, but Enumerable
is also included, so it can be treated like an array.By contrast, thinking that "the plural name-only method of the model is strange because it returns ActiveRecord::Relation
" is not in line with the Rails design concept.
In Ruby, if you say "return more than one object", it is sufficient to include Enumerable.If you need a real array, you just need to add to_a
.
© 2024 OneMinuteCode. All rights reserved.