【问题标题】:rails 4 scopes with NOT equal and associationsrails 4 范围不等于和关联
【发布时间】:2014-06-07 15:09:03
【问题描述】:

我的控制器中有一个实例变量,我正在尝试将其转换为我的模型的范围。

实例变量:产品

@products_with_user_differences = Product.where{|p| p.last_user != p.user.username && p.asset_type.name == "Computer" unless p.user.nil? or p.allow_multi_users == true}

解释:

这会显示 last_user 值不同于 user.username 且类型为 “计算机” 的所有产品。它还排除了 user_id:nilallow_multi_users 属性设置为 TRUE 的任何产品。

我尝试了以下零运气:Products.rb

scope :with_user_differences, -> { where(last_user != user.username && asset_type.name == "Computer" unless user.nil? or allow_multi_users == true)}

它似乎无法识别关联或在范围内允许“!=”。

有什么想法或建议吗?

【问题讨论】:

  • 在第一个版本中使用where{,在第二个版本中使用where(A normal ActiveRecord where 绝对不能在你的范围内做你想做的事情。
  • 谢谢,但我已经意识到它不能这样做,因为它不起作用。有关正确方法的任何提示?
  • 对不起,如果您认为我的评论没有帮助。我认为它会帮助您了解 为什么 它不起作用。我在其中放置了一个链接,在尝试重写您的查询时可能会有所帮助。

标签: ruby-on-rails associations scopes


【解决方案1】:

以下代码将返回与userasset_type 关联的产品

Product.joins(:user, :asset_type)

排除 allow_multi_users 设置为 true 的产品

Product.where(allow_multi_users: false)

要获得asset_type.namecomputer 的产品,假设您遵循约定并且asset_type 位于名为asset_types 的表下

# take note of the pluralized asset_type
Product.where(asset_types: { name: 'Computer' })

获取last_user 不等于关联用户的用户名的产品

Product.where('products.last_user != users.username')

鉴于所有这些,您可以执行以下操作

def self.with_user_differences
  Product
    .joins(:user, :asset_type)
    .where(assset_types: { name: 'Computer' })
    .where(allow_multi_users: false)
    .where('products.last_user != users.username')
end

【讨论】:

  • 您错过了asset_type.name == "computer" 条件
猜你喜欢
  • 2016-07-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-09
相关资源
最近更新 更多