0

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?

Kostas Rousis
  • 5,918
  • 1
  • 33
  • 38
hacosglez
  • 31
  • 4
  • If it's always a first and secondary category, can't you simply model it as such? For example, give `Recipe` `primary_category` and `secondary_category` attributes which point to two `Categories`? – Daniël Knippers May 16 '14 at 14:31
  • @DaniëlKnippers This is one of the first solutions that came to my mind. However, I think such changes causes to mess some things up, so I prefer something simpler. – hacosglez May 16 '14 at 16:36

2 Answers2

1

I don't think you can control ordering using has_and_belongs_to_many. As for me I don't like use such kind of references because of a little flexibility.

I prefer (and suggest you) to use a "normal" model/table to connect Recipe and Category. This model (CategoryRecipe) can have additional fields such as position or additional flags such as main. This way will give you a lot of advantages.

gotva
  • 5,919
  • 2
  • 25
  • 35
0

Rails has_and_belongs_to_many associations (actually, all Rails association types) are not designed to be order-preserving. However, you can add this functionality to associations using the acts_as_list gem.

An example of implementing ordered has_and_belongs_to_many associations using acts_as_list with has_many can be found in answer to this question.

Community
  • 1
  • 1