为什么Rails模型没有将值写入数据库?

时间:2014-10-29 15:14:03

标签: mysql ruby-on-rails model database-migration

我是Rails的新手,除了将正确的值写入de database之外,我的应用程序正在按预期执行所有操作,每个模型实例都已创建,但传递给它的所有值都为null。

Github链接到应用程序: https://github.com/aldeano19/railsLearn

模型

class Oneinfo < ActiveRecord::Base
  attr_accessor :name, :number

end

控制器

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

查看

<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%> &nbsp 
  <%=val%><br>
<%end%>

** 7个模型被提交后的MYSQL数据库**

+----+------+--------+---------------------+---------------------+
| 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 |
+----+------+--------+---------------------+---------------------+

1 个答案:

答案 0 :(得分:0)

从Oneinfo模型中删除attr_accessor :name, :number

attr_accessor为您的班级创建实例方法(读者和作者)。所以,例如,而不是:

class Car
  # reader
  def engine
    @engine
  end

  #writer
  def engine=(engine)
    @engine = engine
  end
end

你可以写:

class Car
  attr_accessor :engine
end

这里的线索是attr_accessor :name, :number会覆盖模型字段的默认行为。在实际情况中,您不需要为任何模型字段指定attr_accessor,除非您需要使用一些额外字段扩展模型,这些字段未在数据库表中定义。