通过基于模型属性 has_many 关系进行过滤,rails 3?
我有一个简单的问题,但似乎找不到任何解决方案,尽管我找到了类似的东西,但不完全是我正在寻找的东西。
我有一个应用程序,其中用户通过 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要
current_user.assets
,那么您的范围应该可以工作。哦,但是你想要 user_assets。唔。我认为您需要
:include
子句来find()
但将它放在哪里,我现在无法想到。也许
(我还没有使用 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 tofind()
but where to put it, I can't be arsed to think of right now.Perhaps
(I'm not on Rails 3 yet, so that's going to be mangled)
Are you using
:through
when you really want a HABTM?