I'm currently developing a Rails application which operates with two models: Recipes
and Categories
. They are both related by a has_and_belongs_to_many relationship.
In the Recipes form, the user has the possibility to add two different categories (the first will be the main category and the second will be the secondary one).
To reach this, I've added the following code to the controller (in the corresponding view, they both are dropdown menus named category[0] and category[1] respectively):
categories = params[:category]
categories.each do |c|
@recipe.categories << Category.find_by_id(c)
end
Although this code works, it does not work as I expected because the association is constructed by id ordering (for example, if the main category has id=3 and the secondary one has id=1, their order will be always changed).
Is there a way to indicate the desired order when using the <<
operator? Any suggested modification?