2014-10-29 82 views
0

我是Rails的新手,除了向數據庫寫入正確的值之外,我的應用程序正在按照預期完成所有工作,每個模型實例都已創建,但傳遞給它的所有值均爲空。爲什麼Rails模型不會將值寫入數據庫?

Github上鍊接到應用:https://github.com/aldeano19/railsLearn

模型

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

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數據庫已經被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 | 
+----+------+--------+---------------------+---------------------+ 
+1

如果從模型中刪除'attr_accessor:name,:number'會怎麼樣? – blelump 2014-10-29 15:18:06

+0

請更具說明性。 「drop」是什麼意思,這是否意味着刪除模型中的'attr_accessor:name,:number',將其從數據庫中刪除?對不起,我只是對Rails非常陌生。 – 2014-10-29 15:21:10

+1

更具體地說:從'Oneinfo'模型中刪除該行。 – blelump 2014-10-29 15:22:02

回答

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,除非您需要使用一些額外的字段來擴展模型,這些字段在數據庫表中沒有定義。

+0

感謝您的詳細解釋。很有幫助。 – 2014-10-29 15:47:20

相關問題