【问题标题】:Filter based on model attribute has_many relationship through, rails 3?基于模型属性has_many关系过滤,rails 3?
【发布时间】:2011-07-06 23:59:08
【问题描述】:

我有一个简单的问题,但似乎找不到任何解决方案,虽然我找到了相似的东西,但不完全是我想要的。

我有一个应用程序,其中用户通过 UserAsset 类拥有许多资产。我希望能够执行 current_user.user_assets ,但我只想返回具有指定字段值为“活动”的资产的记录。

这个post 类似,但我需要使用主模型而不是连接模型作为过滤器。

class UserAsset < ActiveRecord::Base
  belongs_to :asset
  belongs_to :user
end

class Asset < ActiveRecord::Base
  has_many :user_assets
  has_many :users, :through => :user_assets
end

class User < ActiveRecord::Base
  has_many :user_assets
  has_many :assets, :through => :user_assets
end

我尝试在 Assets 上设置默认范围,以及在 has many (user_assets) 关系上设置一些条件,但 rails 未能考虑 Assets 表上的连接。即“where 子句”中的未知列“asset.live”。努力实现以下目标:

 @active_user_assets = current_user.user_assets  #only where assets.active = true

那么我如何使用条件或范围来实现这一点?我需要 user_asset 对象,因为它包含有关相关关系的信息。

提前致谢!

【问题讨论】:

    标签: ruby-on-rails-3 scope has-many-through


    【解决方案1】:

    你想要current_user.assets,那么你的作用域应该可以工作。

    哦,但你想要 user_assets。唔。我认为你需要 :includefind() 的子句,但我现在想不起来。

    也许

    current_user.user_assets.find(:all, :include => :assets).where('asset.live=?', true)
    

    (我还没有使用 Rails 3,所以它会被破坏)

    当您真的想要一个 HABTM 时,您是否使用 :through

    【讨论】:

    • 我不能使用HABTM,因为我需要额外的关系字段。不过,您的提示确实帮助我找到了解决方案:我在 User.rb 的“has_many :user_assets”行中添加了“:include => :asset,:conditions =>”assets.active='1'"",现在它完美地工作,虽然我不肯定这是最佳/适当的解决方案性能明智。我会花几分钟看看其他人是否有更好的主意。谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-14
    • 1970-01-01
    相关资源
    最近更新 更多