如何使用 ActiveRecord 和 Rails 让急切加载的条件稍后延迟加载
首先让我展示一些代码。
class User
has_and_belongs_to_many :roles
named_scope :employees, { :conditions => ["roles.name = 'Employee'"], :include => :roles }
end
好的,所以稍后在控制器中我想正确搜索所有员工。 我设置了命名范围来帮助通过连接和条件搜索来完成此操作。 但问题是在视图中我想显示所有用户角色,但它只会显示员工角色。
无论如何,我可以说“user.roles”并在我已经急切加载它之后将其延迟加载到视图中吗?
First let me show some code.
class User
has_and_belongs_to_many :roles
named_scope :employees, { :conditions => ["roles.name = 'Employee'"], :include => :roles }
end
OK, so later in a controller I wanted to search for all the employees right. I set the named scope up to help do that with the join and conditional search. But the problem is in the view I want to show all of that users roles, but It will only display the employee role.
Is there anyway that I can say "user.roles" and have the be lazy loaded in the view after I have already eager loaded it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
habtm
的文档 (以及has_many
)指出您可以使用可选参数访问该集合:您可以使用
user.roles(true)
重新加载角色。The documentation for
habtm
(as well ashas_many
) states that you can access the collection with an optional parameter:You can reload the roles with
user.roles(true)
.