I know it has been asked many times, but i could not find any working
examples even after 2 days for googling. So, i thought let me ask here.
How do I save in HABTM
Its a simple application where users should be able to post recipes and
that recipe HABTM categories. Multiple categories are selected through
multi select list box.
- I have 2 models: Recipe and Category
- I have one join table: categories_recipes (category_id, recipe_id)
Now this is in my controller:
class RecipesController < ApplicationController
def new
@recipe = Recipe.new
@categories = Category.find(:all)
end
def create
@recipe = Recipe.new(params[:recipe])
@recipe.category_recipe_ids[]<<(params[:category_recipe_ids])
@recipe.save
redirect_to :action=>‘show’, :id=>@recipe.id
end
def show
@recipe=Recipe.find(params[:id])
end
end
My new.html.erb
<% form_for :recipe, @recipe, :url => { :action => “create” } do |f| %>
<%= f.text_field :title, :maxlength => 100 %>
<%= f.text_area :description, :rows=>‘xx’, :cols=>‘yy’ %>
<%= select_tag ‘category_recipe_ids[]’,
options_from_collection_for_select(@categories, :id, :title), {
:multiple => true, :size =>5, :id => “categories_recipes_id” } %>
<%= submit_tag ‘save’,
:style=>‘font-size:14px;font-weight:bold;width:100px’ %>
<% end %>
Any help is much appreciated.