".save"只在数据库中插入空值

编程入门 行业动态 更新时间:2024-10-25 08:16:12
本文介绍了".save"只在数据库中插入空值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试为一家医院提出RoR申请,以便该医院拥有患者,医生,办公室等.

I'm trying to make a RoR application for a Hospital so it has patients, doctors, offices, etc.

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

The problem I'm having is that, at the patient "Sign-up", I'm not able to save the new patient in the database. In fact, despite I've checked that the attributes are ok (It's just a name and a personal ID), once the method is excecuted, in the database only appears a new row with "<null>" instead of the actual attribute values. Here's the method:

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

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

Also, This is the query that it constructs:

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信息后,将调用此方法:

This method is called after some other view collects the :name and :pid information in this form:

<%= 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也是如此.

Needless to say, pat.errors.empty? is true, and so is 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

推荐答案

删除class Patient中的以下行:

attr_accessor :name, :pID

发生了什么事, attr_accessor替换了两个数据库列属性 :name和:pID(它们是自动生成的)具有自己的属性,从而产生两个虚拟属性: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.

更多推荐

".save"只在数据库中插入空值

本文发布于:2023-10-25 22:22:05,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1528275.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:只在   数据库中   quot   save

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!