如何在模型中存储日期?

时间:2016-02-29 20:42:24

标签: mysql ruby-on-rails date model

我正在使用Rails 4.2.3和MySql 5.5.37。我有一个基于以下数据库表的模型...

mysql> desc user_objects;
+------------+--------------+------+-----+---------+----------------+
| Field      | Type         | Null | Key | Default | Extra          |
+------------+--------------+------+-----+---------+----------------+
| id         | int(11)      | NO   | PRI | NULL    | auto_increment |
| user_id    | int(11)      | YES  | MUL | NULL    |                |
| object     | varchar(255) | YES  |     | NULL    |                |
| day        | date         | YES  |     | NULL    |                |
| total      | int(11)      | YES  |     | NULL    |                |
| created_at | datetime     | NO   |     | NULL    |                |
| updated_at | datetime     | NO   |     | NULL    |                |
+------------+--------------+------+-----+---------+----------------+

在我的控制器中,我正在尝试处理从表单提交的参数,因此我使用此...

def create
  @current_user = User.find(session["user_id"])
  …
  puts user_object_params
  @user_object = UserObject.new(user_object_params)
  puts @user_object.object 
  puts @user_object.day 
  puts @user_object.total

即使第一个“puts”行打印出“{”object“=>”3“,”day“=>”02/28/2016“,”total“=>”77“}” ,第三行put(“@ user_object.day”)打印出来。通过“新”调用,我需要做什么才能在模型中创建日期对象?

编辑:以下是文件“./app/models/user_object.rb”中user_object的定义。

class UserObject < ActiveRecord::Base

  validates :day, :presence => true
  validates_numericality_of :total
  validates :object, :presence => true

  def self.find_total_by_user_object_month_and_year(user_id, object, month, year)
    sum(:total, :conditions => ['user_id = ?', user_id, 'object = ?', object, 'month(day) = ?', month, 'year(day) = ?', year])
  end

  def self.find_total_by_user_object_and_year(user_id, object, year)
    sum(:total, :conditions => ['user_id = ?', user_id, 'object = ?', object, 'year(day) = ?', year])
  end

end

编辑2:响应给出的答案,包括在我的控制器中

  puts user_object_params[:day] 
  @user_object.day = user_object_params[:day]
  puts @user_object.day

首先打印出“02/23/2016”,然后打印第二个“放置”,但是没有打印出第二个“放置”。

2 个答案:

答案 0 :(得分:0)

看起来你的params是正确的,但是要检查问题是否在require File.dirname(__FILE__) + '/spec_helper' describe 'admin' do before :all do @student=FactoryGirl.create(:student) end it 'should save student information' do params={ post:{ first_name: 'Abraham', last_name: 'Lincoln', address: '1400 Pennsylvania Ave.', city: 'Washington', state: 'D.C.', zip: '11111', email: 'alincoln@whitehouse.gov', password: 'I cant tell a lie', major: 'Law', level: 'Graduate', employment: 'President', participation: 'Yes', participation_research: 'No', what_doing_now: 'Watching a Play', ethnicity: 'White', eth_other: 'none', education_level: 'Doctorate', hometown: 'Springfield, IL', twitter_handle: '@TheRealAbe', facebook_url: 'therealabe', prior_education: 'None', prior_AS: 'None', prior_BS: 'None', prior_MS: 'None', prior_Other: 'None', awards_honors: 'Ended Civil War', scholarships: 'Full', other_inbre_funding: 'yes', deleted: 'false' } } post '/admin/students/add/', params, {'rack.session'=>{student_id:@student.id, admin_authorized:true}} updated_student = Student.get(@student.id) expect(updated_student.first_name).to eql('Abraham') #expect(updated_student.last_name).to eql('Dick') #expect(updated_student.address).to eql('1400 Pennsylvania Ave.') end end 部分,你可以尝试单独分配值

UserObject.new(user_object_params)

然后尝试打印值。

我感觉属性@user_object = UserObject.new @user_object.object = user_object_params[:object] @user_object.day = user_object_params[:day] @user_object.total = user_object_params[:total] 与某些rails内部属性冲突。

要对此进行测试,您可以单独指定除object attr之外的值。或删除散列中的object键。

答案 1 :(得分:0)

打开答案,但预计会需要一些迭代。

假设@user_object.object@user_object.total行为正常(您需要确认这一点),我怀疑您遇到了棘手的Ruby Date(或相关)问题。

确保(a)@user_object.day以您想要的格式定义(在迁移中)(存储字符串,日期或日期时间?)和(b)user_object_params[:day]格式的格式与迁移中定义的类型相匹配。

众所周知的subleties(读取,差异)是Ruby和Rails处理日期和日期时间的方式。也许这是你问题的根源。

要将日期字符串转换为DateTime,您必须执行以下操作:

DateTime.strptime("06/18/2013", "%m/%d/%Y")

正如所讨论的那样here。因此,可能在执行@user_object.new(user_object_params)之前,您可能需要执行以下操作:

user_object_params[:day] = DateTime.strptime(user_object_params[:day], "%m/%d/%Y")

在这里钓鱼,但认为这可能会有所帮助。