2

我正在尝试为医院制作 RoR 应用程序,以便它拥有患者、医生、办公室等。

我遇到的问题是,在患者“注册”时,我无法将新患者保存在数据库中。事实上,尽管我检查了属性是否正常(它只是一个名称和个人 ID),但一旦执行该方法,在数据库中只会出现一个带有“<null>”的新行,而不是实际的属性值. 这是方法:

def pat_create

  pName = params[:name].to_s
  id    = params[:pid].to_s.to_i

  pat = Patient.where(:pID => id).first
  if pat == nil
    pat = Patient.new(:name => pName, :pID =>id)
    pat.save
  end

end

此外,这是它构造的查询:

INSERT INTO `patients` (`created_at`, `name`, `pID`, `updated_at`) VALUES ('2013-05-20 02:04:28', NULL, NULL, '2013-05-20 02:04:28')

在其他视图以这种形式收集 :name 和 :pid 信息后调用此方法:

<%= form_tag('/page/pat_create') do %> 
  <%= text_field_tag :name, nil%> 
  <%= text_field_tag :pid, nil%> 
  <%= button_tag(type: "submit", class: "btn btn-success") do %> 
    Register<i class="icon-white icon-plus"></i> 
  <%end%> 
<%end%>

不用说,pat.errors.empty?是真的,也是pat.save

知道为什么会这样吗?

这是患者模型:

class Patient < ActiveRecord::Base

  attr_accessible :name, :pID
  attr_accessor :name, :pID

  has_many :appointments
  validates_presence_of :name
  validates :name, :format => {:with=> /^[a-zA-Z\s\D]+$/}
  validates_presence_of :pID
  validates_numericality_of :pID
  validates_inclusion_of :pID, :in => 100000..9999999999   

end
4

3 回答 3

5

Remove the following line in class Patient:

attr_accessor :name, :pID

What happened was that attr_accessor replaced the two database column attributes :name and :pID (which were automatically generated) with its own, resulting in two virtual attributes, :name and :pID.

Thus, the virtual attributes were being set and validated instead of the corresponding database attributes, which resulted in no errors yet null values in the database.

于 2013-05-21T02:07:46.070 回答
-1

你能告诉我们这个方法是怎么调用的吗?你也确定 params[:name] 和 params[:pid].

您已经使用了 :pid 和 :pID 列,如下所示

pat = Patient.where(:pID => id).first
if pat == nil
  pat = Patient.new(:name => pName, :pID =>id)  # should use pat = Patient.new(:name => pName, :pid =>id)
  pat.save
end
于 2013-05-20T02:52:45.840 回答
-1

因此,在您的控制器中,您的参数为零,但您调用.to_s.to_s.to_i会导致空字符串“”和 0(零)。然后将它们保存到数据库中。几个建议:

def pat_create

  pat = Patient.new(:name => params[:name], :pid =>params[:pid])
  pat.save

end

除了唯一性验证之外,我还会确保您的 db 列上有一个唯一索引,以确保没有重复的患者。

class Patient < ActiveRecord::Base

  attr_accessible :name, :pid
  attr_accessor :name, :pid

  has_many :appointments
  validates :name, presence: true, 
                   length: { maximum: 50 }, 
                   format: {:with=> /^[a-zA-Z\s\D]+$/}
  validates :pid, presence: true,
                  numericality: { only_integer: true, 
                                  greater_than_or_equal_to: 100000, 
                                  less_than_or_equal_to: 9999999999 },
                  uniqueness: true
end

如果您获得有效值,这将起作用,如果没有,您将看到为什么它不是。

于 2013-05-20T05:01:13.773 回答