I am new to Rails and my applications is doing everything as intended except writing the right values to de database, each model instance is created but all values passed to it are being null.
Github link to application : https://github.com/aldeano19/railsLearn
Model
class Oneinfo < ActiveRecord::Base
attr_accessor :name, :number
end
Controller
class InfoController < ApplicationController
$names = {}
@show = true
def print
if request.request_method_symbol == :get
$names = {}
@show = false
else
@show = true
name = params[:myinfo][:name]
number = params[:myinfo][:number]
$names[name] = number
@newinfo = Oneinfo.new(oneinfo_params)
@newinfo.save
end
end
private
def oneinfo_params
params.require(:myinfo).permit(:name, :number)
end
end
View
<h1>Info print</h1>
<%= form_for :myinfo do |a| %>
<%= a.label :name %>
<%= a.text_field :name %><br>
<br>
<%= a.label :number%>
<%= a.text_field :number%><br>
<br>
<%= a.submit %>
<%end%>
<div id="clear" style="display: <%= @show ? 'inline' : 'none' %> ">
<%= form_for :button do |b|%>
<%link_to 'clear', info_print_path %>
<%end%>
</div>
<% $names.each do |key, val|%>
<%=key%>  
<%=val%><br>
<%end%>
** MYSQL Database after 7 Models have being submited**
+----+------+--------+---------------------+---------------------+
| id | name | number | created_at | updated_at |
+----+------+--------+---------------------+---------------------+
| 1 | NULL | NULL | 2014-10-28 19:28:14 | 2014-10-28 19:28:14 |
| 2 | NULL | NULL | 2014-10-28 23:32:31 | 2014-10-28 23:32:31 |
| 3 | NULL | NULL | 2014-10-28 23:32:37 | 2014-10-28 23:32:37 |
| 4 | NULL | NULL | 2014-10-28 23:33:10 | 2014-10-28 23:33:10 |
| 5 | NULL | NULL | 2014-10-28 23:33:32 | 2014-10-28 23:33:32 |
| 6 | NULL | NULL | 2014-10-28 23:33:34 | 2014-10-28 23:33:34 |
| 7 | NULL | NULL | 2014-10-28 23:33:43 | 2014-10-28 23:33:43 |
+----+------+--------+---------------------+---------------------+
Delete attr_accessor :name, :number
from Oneinfo model.
attr_accessor
creates instance methods (reader and writer) for your class. So, for instance, instead of having:
class Car
# reader
def engine
@engine
end
#writer
def engine=(engine)
@engine = engine
end
end
you can write:
class Car
attr_accessor :engine
end
The clue here is that attr_accessor :name, :number
overrides the default behaviour of your model fields. In real cases, you do not need to specify attr_accessor
for any of your model fields, unless you would need to extend your model with some extra fields, which are not defined in your database table.