如何以服务于轨道的形式从一个对象的数据关联? [英] How to I serve data from an object's associations in rails forms?

查看:171
本文介绍了如何以服务于轨道的形式从一个对象的数据关联?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有我开发一个控制器有许多属性的对象。然而,由于数据模型我创建,大部分我有编辑属性都是通过其他表关联保存。 EG:我有必须通过表的Tagging标签(并保存在其他表20其他属性)的文章。文章必须通过多态关联等许多其他属性。

I have an object that I am developing a controller for that has many attributes. However, due to the data model I have created, most of the attributes that I have to edit are saved through associations in other tables. EG: I have articles that have tags through a taggings table (and about 20 other attributes saved in other tables). THe article has many other attributes through polymorphic associations etc..

该协会工作的伟大,并启用每个属性的多个条目的保存。然而,有一件事是困难的是精简编辑操作的控制器。通常你可以只保存@article = Article.find(PARAMS [:ID])和所有属性显示出来。这意味着该形式具有当前属性服务,并且该人可以只进行更改。

The associations work great, and enable the saving of multiple entries of each attribute. However, one thing that is difficult is streamlining the edit action to the controller. Usually you can just save @article = Article.find(params[:id]) and all of the attributes show up. This means that the form has the current attributes served, and the person can just make changes.

不过,对于通过关联保存的东西,这些字段是空的。我有一个毒刃解决方案,由此我做的,例如,@ article.tag_list = @ article.tags.map(安培;:名)。这让字段现在显示的标签。

However, for stuff saved through association, those fields are empty. I have a shiv solution whereby I do, for example, @article.tag_list = @article.tags.map(&:name). This lets the field now show the tags.

但是,这样做对每个属性增加了这么多的线路在控制器编辑操作。有没有更好的办法?

However, doing this for each attribute adds so many lines to the edit action in the controller. Is there a better way?

如果有一些code我应该张贴,我可以 - 只是没有,因为它是混乱的,现在,所以我想我会解释,而不是

If there is some code I should post, I can - just didn't because it's messy right now, and so I thought I would explain instead.

推荐答案

您需要的是渴望负荷的关联 - 这仅仅意味着填充协会与基本对象一起,当你加载它。退房在页。

What you want is to "eager load" the associations -- which simply means to populate the associations along with the base object when you load it. Check out the "Eager loading of associations" section on this page.

这篇关于如何以服务于轨道的形式从一个对象的数据关联?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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