How to I serve data from an object's associati

2019-08-27 20:16发布

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条回答
虎瘦雄心在
2楼-- · 2019-08-27 20:50

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.

查看更多
登录 后发表回答