HI,
I have this type of code where I used a modeling like
‘user.profile_photo’ from user object I am trying to find profile
photo.but it is happened in a loop so just I want to know that how
modeling works ? Internally it is a query if so then executing such
thing inside a loop is a expensive. so when to use query and when to use
modeling any feasible solution for a such a problem.
e.g:-
@group=Group.find(group_id)
[email protected]_accepted
for user in group_users
if !@profile_user.include?(user)
if !user.profile_photo.nil?
@profile_user << user
end
end
end
hello,
@users = User.invitation_accepted
@users.each { |user| @profile_user << user if (@profile_user.include?
(user) and user.profile_photo.nil?) }
in your model:
named_scope :grouped, lambda { |id| { :include => :groups, :conditions
=> “groups.id = #{id} and groups.user_id = user.id” } }
def invitation_accepted
User.grouped.find …
end
untested
On 21 Aug., 06:43, Sunny B. [email protected]
what is named_scope and how it is useful in a performance perspective?
named_scope is a smart way to chain model find options with synonyms
but here it isn’t responsible for the query optimization
look at :include
it iniate a join with group
so your 2 queries are reduced to one query
look at your development.log to see, what activerecord is building for
you
and if your query looks good
hint: look for some basic active records tutorial, espacially for
eager loading and lazy loading
best regards
On 21 Aug., 09:21, Sunny B. [email protected]