ruby-on-rails - Rails的named_scope问题与急切加载

发布于 2024-09-06 02:27:40 字数 857 浏览 6 评论 0原文

两种模型(Rails 2.3.8):

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

我正在尝试创建一个named_scope来消除disabled=1和hidden=1用户配置文件。此外,虽然用户模型通常与配置文件模型结合使用,但我希望能够灵活地使用 :include => 来指定它。 :配置文件语法。

我有以下用户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>

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

Two models (Rails 2.3.8):

User; username & disabled properties; User has_one :profile
Profile; full_name & hidden properties

I am trying to create a named_scope that eliminate the disabled=1 and hidden=1 User-Profiles. Moreover, while the User model is usually used in conjunction with the Profile model, I would like the flexibility to be able specify this using the :include => :profile syntax.

I have the following User named_scope:

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

This works as expected when just reference the User model:

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

However, when I attempt to include the Profile model:

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

I get an error that reads:

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

Am I able to cross model-collection boundaries in this manner?

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

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

发布评论

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

评论(1

潦草背影 2024-09-13 02:27:40

要访问用户个人资料,您必须使用类似的东西,

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

或者,如果您想要的是所有full_name,我相信您应该做类似的事情

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

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

To access a user's profile, you have to use something like

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

Or, if what you want is all full_names, I believe you should do something like

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

But probably there's a better way... It doesn't look pretty =P

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