ruby-on-rails - Rails的named_scope问题与急切加载
两种模型(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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
要访问
用户
的个人资料
,您必须使用类似的东西,或者,如果您想要的是所有
full_name
,我相信您应该做类似的事情但可能有更好的方法...它看起来不太漂亮=P
To access a
user
'sprofile
, you have to use something likeOr, if what you want is all
full_name
s, I believe you should do something likeBut probably there's a better way... It doesn't look pretty =P