通过基于模型属性 has_many 关系进行过滤,rails 3?

发布于 2024-10-19 20:33:47 字数 948 浏览 1 评论 0原文

我有一个简单的问题,但似乎找不到任何解决方案,尽管我找到了类似的东西,但不完全是我正在寻找的东西。

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

帖子类似但我需要使用主模型而不是连接模型作为过滤器。

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

我尝试设置资产的默认范围,以及具有许多(user_assets)关系的一些条件,但rails未能考虑资产表上的联接。即“where 子句”中的未知列“asset.live”。尝试实现以下目标:

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

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

提前致谢!

I have a simple question, but can't seem to find any solution, though I have found things that are similar, but just not exactly what I am looking for.

I have an application where a User has many Assets through the class UserAsset. I want to be able to do current_user.user_assets , but I only want to return records that have an Asset with a specified field value of "active".

This post is similar but I need to use the main model not the join model as a filter.

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

I tried setting the default scope on Asset, and also some conditions on the has many (user_assets) relationship, but rails is failing to consider the join on the Assets table. ie Unknown column 'asset.live' in 'where clause'. Trying to achieve the following:

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

So how do I use conditions or scopes to achieve this? I need the user_asset object because it contains info about the relationship that is relevant.

Thanks in advance!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

风筝在阴天搁浅。 2024-10-26 20:33:47

您需要 current_user.assets,那么您的范围应该可以工作。

哦,但是你想要 user_assets。唔。我认为您需要 :include 子句来 find() 但将它放在哪里,我现在无法想到。

也许

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

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

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

You want current_user.assets, then your scopes should work.

Oh, but you want the user_assets. Hmm. I think you need the :include clause to find() but where to put it, I can't be arsed to think of right now.

Perhaps

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

(I'm not on Rails 3 yet, so that's going to be mangled)

Are you using :through when you really want a HABTM?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文