Search code examples
ruby-on-railsrubyruby-on-rails-7

RubyOnRails use .where query with has_one - belongs_to relationship


Should i always use plural model name when using .where query with has_one relationship?

My models

class User < ApplicationRecord
  has_one :role
end

class Role < ApplicationRecord
  belongs_to :user
end

.where query examples

# 1
role = Role.first
User.joins(:role).where(role: role)
# 2
role = Role.first
User.joins(:role).where(roles: role)

Both of them have no issues with execution, but which one is correct? (I would appreciate it if you could give me a link if there is a revised PR from ROR's future version)

My ruby on rails version => 7.0.4


Solution

  • It's always better to use the plural form when doing that, because it corresponds to the table name, when you use the singular form, rails assigns an alias so in your example it becomes,

    INNER JOIN roles role ON role.user_id = users.id

    See what happened there? it became an alias of the actual table name. Hope this answers your main question.