使用fields_for时如何将范围应用于关联? [英] How to apply a scope to an association when using fields_for?

查看:30
本文介绍了使用fields_for时如何将范围应用于关联?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个有很多任务的项目,每个任务属于一个人.

I have a Project having many Tasks, and each Tasks belongs to a Person.

在我的项目编辑表单中,我允许编辑现有任务并使用嵌套对象表单工具添加新任务 (http://ryandaigle.com/articles/2009/2/1/what-s-new-in-edge-rails-nested-attributes):

In my Project edit form, I permit to edit existing tasks and add new ones with the Nested Object Form facility (http://ryandaigle.com/articles/2009/2/1/what-s-new-in-edge-rails-nested-attributes):

<% project_form.fields_for :tasks do |task_form| %>

我想在 fields_for 从数据库请求任务时急切加载关联的 Task Person 对象,但我找不到解决方案.是否可以?在 Project 模型中,我可以使用 :include 选项定义我的 has_many :tasks,但我宁愿避免这种情况,因为我通常在处理项目任务时不需要急切加载 Person 对象.

I want to eager load the associated Task Person objects when fields_for requests the tasks from the database, but I could not find a solution. Is it possible? In the Project model I could define my has_many :tasks with the :include option, but I would rather avoid this as I don't need to eager load Person objects when dealing with a project tasks in general.

现在我已经创建了第二个 has_many 关联:tasks_including_person 与相应的 accepts_nested_attributes_for 并在我的 fields_for 中使用它.它有效,但我不想创建这样的特定关联.

For now I've created a second has_many association :tasks_including_person with the corresponding accepts_nested_attributes_for and use it in my fields_for. It works but I would prefer not have to create a specific association like this.

推荐答案

您可以将第二个参数传递给 fields_for,它是要呈现的对象或集合.例如:

You can pass a second parameter to fields_for which is the object or collection to render. For example:

project_form.fields_for :tasks, project_form.object.tasks.all(:include => :person) do |task_form|

这篇关于使用fields_for时如何将范围应用于关联?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆