Sorry in advance if this question is very simple. I was looking for
advice or a link to help with the following issue.
Let’s say I have an app where I have categories of food like
‘Meat’,‘Dairy’,‘Fruit’ and the MVC functionality of this works well
already.
Now I create another sub-application where I add certain items of food
like ‘Orange’,‘Chicken’,‘Milk’, but I want to allow a user to pick
which category a particular item belongs to. Is there an automated way
of getting such an html select box with categories displayed?
BTW, I have successfully done this already, but I am afraid that I am
not harnessing the potential of RoR entirely here.
THANKS IN ADVANCE,
David
My sequence:
- create tables
- create models
- create scaffolding
- modify items_controller
- modify _form.html for items to allow for an html select to be
created
Please offer any alternatives to what I have already done below:
tables= categories, items
–each have their own id
–items also has category_id
class Item < ActiveRecord::Base
belongs_to :category
validates_associated :category
end
class ItemsController < ApplicationController
def index
list
render :action => ‘list’
end
def list
@Item_pages, @Items = paginate :Item, :per_page => 10
end
def show
@Item = Item.find(params[:id])
end
def new
@categories=Category.find_all
@Item = Item.new
end
def create
@Item = Item.new(params[:Item])
if @Item.save
flash[:notice] = ‘Item was successfully created.’
redirect_to :action => ‘list’
else
@categories=Category.find_all
render :action => ‘new’
end
end
def edit
@categories=Category.find_all
@Item = Item.find(params[:id])
end
def update
@Item = Item.find(params[:id])
if @Item.update_attributes(params[:Item])
flash[:notice] = ‘Item was successfully updated.’
redirect_to :action => ‘show’, :id => @Item
else
render :action => ‘edit’
end
end
def destroy
Item.find(params[:id]).destroy
redirect_to :action => ‘list’
end
end
_form.rhtml
<%= error_messages_for ‘item’ %>
Item
<%= text_field 'item', 'item' %>
Description
<%= text_field 'item', 'description' %>
<%=options_from_collection_for_select @categories, "id", "category",@item.category_id%>
Created on
<%= datetime_select 'item', 'created_on' %>
Updated on
<%= datetime_select 'item', 'updated_on' %>