Sunday, June 19, 2011

rails fields_for, object sorting

So what I needed to do was select a subset of one model which happened to have a key into another, sort it by an attribute of the other model, and display a list of the results in a form.
here's the query to find, filter, join, and order:
@user_categories = Category.joins(:user_categories).where('user_categories.user_id' => current_user.id).order("name asc")


and here's the bit of the form:

<%= f.fields_for :user_categories, @user_categories do |user_category| %>


and then to access the objects:

<%= user_category.label :name, user_category.object.name %>



Things to notice:
the fields_for uses a parameter :user_categories which references the name of the model, followed by the object which is actually a list of objects of type Category, so I'm assuming this is to let rails know how to treat it. Also, note that to reference the actual objects, you have to use model_class.object.method. the model_class is actually some sort of form builder helper before the call to .object.

This only took an hour to figure out - #facepalms = 3.