0

两种型号(Rails 2.3.8):

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

我正在尝试创建一个 named_scope 来消除 disabled=1 和 hidden=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 模型时,这将按预期工作:

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

但是,当我尝试包含 Profile 模型时:

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

我收到一条错误消息:

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

我能以这种方式跨越模型集合的界限吗?

4

1 回答 1

0

要访问 a userprofile您必须使用类似的东西

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

或者,如果你想要的都是full_names,我相信你应该做类似的事情

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

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

于 2010-06-12T15:49:28.603 回答