admin管理员组

文章数量:1310178

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

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

Share Improve this question edited Feb 3 at 10:26 52zxc asked Feb 3 at 10:25 52zxc52zxc 32 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 2

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.

本文标签: ruby on railsRubyOnRails use where query with hasonebelongsto relationshipStack Overflow