How to I serve data from an object's associations in rails forms?

你离开我真会死。 提交于 2019-12-25 07:48:28

问题


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..

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.

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?

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.


回答1:


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.



来源:https://stackoverflow.com/questions/8752859/how-to-i-serve-data-from-an-objects-associations-in-rails-forms

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!