2010-06-12 119 views
0

两种型号(Rails 2.3.8):rails named_scope急于加载问题

用户;用户名&禁用属性;用户has_one:个人资料 个人资料;全名&隐藏属性

我想创建一个名为_scope消除残疾= 1和隐藏= 1用户配置文件。此外,虽然User模型通常与Profile模型结合使用,但我希望灵活性能够使用:include =>:profile语法来指定。

我有以下的用户named_scope:

named_scope :visible, { 
    :joins => "INNER JOIN profiles ON users.id=profiles.user_id", 
    :conditions => ["users.disabled = ? AND profiles.hidden = ?", false, false] 
    } 

可正常工作时,只是用户参考模型:

>> User.visible.map(&:username).flatten 
=> ["user a", "user b", "user c", "user d"] 

然而,当我尝试包括档案模式:

User.visible(:include=> :profiles).profile.map(&:full_name).flatten 

我收到一条错误消息:

NoMethodError: undefined method `profile' for #<User:0x1030bc828> 

我可以通过这种方式跨越模型集合边界吗?

回答

0

要访问userprofile,你必须使用类似

@user = User.visible(:include => :profiles) 
@user.first.profile 

或者,如果你想要的是所有full_name S,我相信你应该这样做

# untested 
User.visible(:include=> :profiles).map(&:profile).collect{ |p| p.full_name } 

但可能有更好的办法......它看起来不漂亮= P