Riiiick, you are a star. Atlast we have a working example for HABTM. I
have given here the complete code if anyone needs it.
Problem: A recipe can have many categories and a Category can have many
recipes.
Model: Recipe
class Recipe < ActiveRecord::Base
has_and_belongs_to_many :categories
end
Model: Category
class Category < ActiveRecord::Base
has_and_belongs_to_many :recipes
end
Controller: recipes_controller
class RecipesController < ApplicationController
def new
@recipe = Recipe.new
@categories = Category.find(:all)
end
def create
@recipe = Recipe.new(params[:recipe])
@recipe.save
redirect_to :action=>'show', :id=>@recipe.id
end
def show
@recipe=Recipe.find(params[:id])
end
end
View: New.html.erb
<% form_for :recipe, @recipe, :url => { :action => "create" } do |f| %>
<%= f.text_field :title, :maxlength => 100 %>
<%= f.collection_select :category_ids, @categories, :id, :title, {},
:multiple => true %>
<%= submit_tag 'save',
:style=>'font-size:14px;font-weight:bold;width:100px' %><br>
<% end %>
View: Show.html.erb
<%= @recipe.title %>
<% @recipe.categories.each do |c|%>
<%= c.title %>
<% end %>
--
Posted via http://www.ruby-forum.com/.
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups "Ruby
on Rails: Talk" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/rubyonrails-talk?hl=en
-~----------~----~----~----~------~----~------~--~---