tuka
December 18, 2006, 11:44am
#1
Hi all,
I am having an issue here that i seem not to wrap my head around… I am
making a simple online catalog…
I have 2 models Category and LineItems
where Category has many LineItems
So in the LineItem Model I say:
class LineItem < ActiveRecord::Base
belongs_to :category
Now in my edit form (View) for LineItem called edit.rhtml, with a drop
down list, I wish to select the category and update it in the database.
For that I use the following before the scaffolding code in the (this is
a simple test app I am doing here…).
<%=
@categories = Category.find(:all, :order => “name”).map {|c| [c.name,
c.id]}
select(:category, :id, @categories )
%>
Items come up ok but I cannot seem to update. I believe the select
parameters are ok but could the problem be there or am I missing
something ?
Note that when I use the Edit view, I wish to read the existing
category_id and have it pre-selected for me if it already exists.
TIA,
Tuka
tuka
December 18, 2006, 12:29pm
#2
Please post your corresponding controller code.
tuka
December 18, 2006, 1:11pm
#3
Your controller code seems in order and I just noticed that it’s your
select() statement that needs adjustment. Try:
select(:line_item, :category_id, @categories )
tuka
December 18, 2006, 12:41pm
#4
Here goes… the full listing so that we miss nothing:
class ItemController < ApplicationController
layout ‘home’
def index
list
render :action => ‘list’
end
GETs should be safe (see
http://www.w3.org/2001/tag/doc/whenToUseGet.html )
verify :method => :post, :only => [ :destroy, :create, :update ],
:redirect_to => { :action => :list }
def list
@line_item_pages , @line_items = paginate :line_items, :conditions =>
["category_id = ? ",params[:id]],:per_page => 10
end
def admin_list
@line_item_pages , @line_items = paginate :line_items, :conditions =>
["category_id = ? ",params[:id]],:per_page => 10
end
def show
@line_item = LineItem.find(params[:id])
end
def new
@line_item = LineItem.new
end
def create
@line_item = LineItem.new(params[:line_item])
if @line_item.save
flash[:notice] = ‘LineItem was successfully created.’
redirect_to :action => ‘list’
else
render :action => ‘new’
end
end
def edit
@line_item = LineItem.find(params[:id])
end
def update
@line_item = LineItem.find(params[:id])
if @line_item.update_attributes (params[:line_item])
flash[:notice] = ‘LineItem was successfully updated.’
redirect_to :action => ‘show’, :id => @line_item
else
render :action => ‘edit’
end
end
def destroy
LineItem.find(params[:id]).destroy
redirect_to :action => ‘list’
end
end
tuka
December 18, 2006, 3:13pm
#5
Roderick, Hurray !!
Not only your indication was correct, it helped me find another error,
that the select code was not within the ROR start_form_tag and thus
in the resulting page - thats is why it was not
writing/reading to the DB.
Thank a ton for your time and pointing me in the right direction !!
Cheers,
Tuka