def create @invoiceitems = Invoiceitems.new(params[:invoiceitems]) @invoiceitems[“invoice_id”] = params[:id]
if @invoiceitems.save
flash[:notice] = ‘Invoiceitems was successfully created.’
redirect_to :action => ‘new’,:id => params[:id]
else
render :action => ‘new’
end
end
In the table invoiceitems I have a field called invoice_id which is a
foreign key and the primary key of the table invoices. I need to save
the invoiceid which is in the URL itself (params[:id]) before saving
.How can I do it .
The above method is not storing that .
Naroor, how did you set up the association in your Invoiceitems model?
I suspect either the association is not set up right, or the :id
parameter is not coming in with the request. A functional test for
this action would be a good idea. (goes for all your other actions as
well
As an aside, it will benefit you in the long to be consistent with
plural/singular in naming your identifiers. Consider calling your
class Invoiceitem as opposed to Invoiceitems, same for the instance
variable.
Gerret ,
Another try that I made was to create a hidden text box and add the
params[:id] to that and save the whole contents .There also it didnt
work .
I suggest we clean up the names of your identifies before looking
further at the problem. I think this is where part of the problem
stems from. AFAICT your create method intends to save a single
Invoiceitem, attach it to an Invoice, and then redirect to a screen
where another Invoiceitem may be added.
So I suggest two cleanup steps:
Rename your Invoicesitems class to Invoiceitem. Singular instead of
Plural. That’s the rails convention, and if you follow it, your code
will read much more easily. Same goes for your instance variable @invoiceitems. Make it @invoiceitem instead.
I suspect you used “./script/generate invoiceitems” to create your
controller. You should pass a singular parameter, so re-run
./script/generate like “./script/generate invoiceitem”. That will give
you a class Invoiceitem instead of Invoiceitems (your table must still
be called ‘invoiceitems’, plural. Which makes sense, because it
contains many items).
In your create method, you are using the parameter :id is the
invoice id. Don’t. In your form, have a parameter :invoice_id, and
don’t use the :id parameter. This makes it very clear which class your
id-parameter belongs to. With your current code, you implicitly
initialize @invoiceitems.id to params[:id], which is not what you
want.
With those two changes done your method will look like this:
def create @invoiceitem = Invoiceitem.new(params[:invoiceitem])
if @invoiceitem.save
flash[:notice] = ‘Invoiceitem was successfully created.’
redirect_to :action => ‘list’
else
render :action => ‘new’
end
end
Because we’ve stuck to naming conventions, the line