Graphql-ruby: Cannot access model in resolver function if it has the same name of the predefined type

Created on 11 Jun 2018  路  3Comments  路  Source: rmosolgo/graphql-ruby

In the query_type.rb file, I created a field user with the resolver function, but when I try to execute the query on GraphiQL, the error appear in the server log.

You can see the illustration screenshot below:

Predefined User Type
alt text

Resolver Function and Field of User
Screenshotfrom2018-06-1116-52-09.png

Error in server log
Screenshotfrom2018-06-1116-52-53.png

p/s: I've already had a Active Record Model user.rb in models folder

Most helpful comment

Yes, I agree with @askn's solution.

This is a consequence of how Ruby looks up constants (like User). First, it looks in the current module nesting, and if it finds something, uses that. So:

module Types 
  User # => will look for Types::User 

  def some_method 
    User # => will look for Types::User
  end 
end 

And it will only go to the top-level ::User if Types::User is _not_ found.

So, if you want to access a top-level constant, you have to prefix it with ::, so that Ruby knows you want a top-level constant, not a nested one.

All 3 comments

You can call

::User.find(id)

Yes, I agree with @askn's solution.

This is a consequence of how Ruby looks up constants (like User). First, it looks in the current module nesting, and if it finds something, uses that. So:

module Types 
  User # => will look for Types::User 

  def some_method 
    User # => will look for Types::User
  end 
end 

And it will only go to the top-level ::User if Types::User is _not_ found.

So, if you want to access a top-level constant, you have to prefix it with ::, so that Ruby knows you want a top-level constant, not a nested one.

@rmosolgo @askn Many thanks, you guys saved my day

Was this page helpful?
0 / 5 - 0 ratings

Related issues

jesster2k10 picture jesster2k10  路  3Comments

dsgoers picture dsgoers  路  3Comments

ecomuere picture ecomuere  路  3Comments

crice88 picture crice88  路  3Comments

rylanc picture rylanc  路  3Comments