ruby-on-rails 在范围内使用示例方法返回不正确的结果

w8f9ii69  于 2022-12-01  发布在  Ruby
关注(0)|答案(1)|浏览(134)

user.rb

has_many :users_positions
has_many :positions, through: :users_positions
//users table has position_id as a field, it represents the current position user is associated with

scope :under_25_value, -> { joins(:positions).where('(value * positions.available / 100) in (?)', 0..24) }
scope :under_50_value, -> { joins(:positions).where('(value * positions.available / 100) in (?)', 25..49) }
scope :over_50_value, -> { joins(:positions).where('(value * positions.available / 100) >= ?', 50) }

def current_positions
  value * position.available / 100
end

在rails控制台中,如果我尝试下面的命令,它会返回当前位置为75的用户,但它应该返回低于25的用户。

User.under_25_value

请帮我找出我错在哪里
示例数据

User id: 894, name: "Jack", value: 18, position_id: 3
Position id: 3, available: 100, name: 'Manager'
hgc7kmma

hgc7kmma1#

由于您的用户模型已经有一个position_id列,该列指向您要为每个用户查询的职位,因此您可以定义一个position关联并更新代码,如下所示:

用户.rb

has_many :users_positions
has_many :positions, through: :users_positions
//users table has position_id as a field, it represents the current position user is associated with
has_one :position

scope :under_25_value, -> { joins(:position).where('(value * positions.available / 100) in (?)', 0..24) }
scope :under_50_value, -> { joins(:position).where('(value * positions.available / 100) in (?)', 25..49) }
scope :over_50_value, -> { joins(:position).where('(value * positions.available / 100) >= ?', 50) }

def current_positions
  value * position.available / 100
end

相关问题