Is it possible to "dynamically" join a table only if this table has not joined yet?

I am using Ruby on Rails 3.2.2, and I would like to know if it is possible to "dynamically" join a table if this area is not yet joined. What is it I:

def self.scope_method_name(user)
  joins(:joining_association_name).where("joining_table_name.user_id = ?", user.id)
end

I would like to do something like the following:

# Note: the following code is just a sample in order to understand what I mean.
def self.scope_method_name(user)
  if table_is_joined?(joining_table_name)
    where("joining_table_name.user_id = ?", user.id)
  else
    joins(:joining_association_name).where("joining_table_name.user_id = ?", user.id)
  end
end

Is it possible / advised to do this? If so, how should I / should continue?


, INNER JOIN SQL- ( , , SQL- , , - ), scope_method_name SQL- ( , ).

. SQL (, "ActiveRecord::StatementInvalid: Mysql2::Error: Unknown column 'joining_table_name.user_id' in 'where clause'" ), (, ClassName.scope_method_name(@user) joining_association_name , joining_table_name).

+5
1

loaded?, , . .

if association_name.loaded?
   where("joining_table_name.user_id = ?", user.id)
else
   joins(:joining_association_name).where("joining_table_name.user_id = ?", user.id)
end
-1

All Articles