Hello everyone I’m learning Ruby on rails for a school project but I
keep bumping in to problems (probably because i’m used to java, c++, c#
and php).
I have a simple table in my database and I have a simple form wich
differs from that table. But after some altering of the form values i
have to send the right values to de database.
ok lets post some code so you will understand:
database table:
class CreateUsages < ActiveRecord::Migration
def self.up
create_table :Usages do |table2|
table2.column :User_id, :integer
table2.column :Usage, :float
end
end
def self.down
drop_table :Usages
end
end
the form:
<h1>New usage</h1>
<%= start_form_tag :action=> "create" %>
<%= error_messages_for 'usage' %><br/>
<label for="usage_kilometers">Kilometers</label><br/>
<%= text_field "usage", "kilometers", :size => 10 %><br/>
<label for="usage_liters">Liters</label><br/>
<%= text_field "usage", "liters", :size => 10 %><br/>
<%= submit_tag "Add" %>
<%= end_form_tag %>
piece of the controller:
def create
@usage = Usage.new(params[:usage])
@user=session[:user]
Usage.calculate(@usage.kilometers, @usage.liters, 10)
if request.post?
if @usage.save
Usage.calculate(@usage.kilometers, @usage.liters, 10)
flash[:notice] = 'Usage was successfully created.'
redirect_to :action => 'list'
else
render :action => 'new'
end
end
end
the model
require 'digest/sha1'
class Usage < ActiveRecord::Base
attr_accessor :kilometers
attr_accessor :liters
attr_accessor :user
validates_length_of :kilometers, :within => 1..10
validates_length_of :liters, :within => 1..10
validates_presence_of :kilometers, :liters
def self.calculate(kilometers, liters, user)
usage = Usage.new
usage.User_id = user
usage.Usage = (kilometers.to_i / liters.to_i)
usage.save
end
end
The problem is that every entry my form makes in de database contains
NULL values… instead of the user_id wich i set to an hard 10. or the
usage value wich is calculated…
I am stuck at this part for some time and I experimented a lot… this
code is the closesd I got.