【发布时间】: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