最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

ruby on rails - RubyOnRails use .where query with has_one - belongs_to relationship - Stack Overflow

programmeradmin0浏览0评论

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.

发布评论

评论列表(0)

  1. 暂无评论