vendredi 28 août 2015

active record with ruby (not rails)

I am using active record with ruby (but not rails). I am using sqlite3 which has a test.db on file (not just in-memory). When I run the following code snippet using user.create, it complains about argument error (and when I use use.save, it throws an active record exception. Any idea what I might be doing wrong? Thanks

    require 'rubygems'
    gem 'activerecord'

    require 'sqlite3'
    require 'active_record'

    ActiveRecord::Base.logger = Logger.new(STDERR)
    #ActiveRecord::Base.colorize_logging = false

    ActiveRecord::Base.establish_connection(
      :adapter => 'sqlite3',
      :host => "localhost",
      :database => 'test.db'
    )

    class User < ActiveRecord::Base
        #attr_accessible :email, :full_name
      attr_accessor :email
      attr_accessor :full_name

    validates :email, presence: true, uniqueness: true

      def initialize(email, full_name)
        @email = email
        @full_name = full_name
      end
    end

    puts "full_name for user:"
    full_name = gets.chomp
    puts "email address:"
    email = gets.chomp
    user = User.new(email, full_name)
    #user.save
    user = User.create!(email: '', full_name: '')

Exception in first case (with User.create!):

main.rb:42:in `initialize': wrong number of arguments (1 for 2) (ArgumentError)
        from /var/lib/gems/1.9.1/gems/activerecord-4.2.4/lib/active_record/inheritance.rb:61:in `new'
        from /var/lib/gems/1.9.1/gems/activerecord-4.2.4/lib/active_record/inheritance.rb:61:in `new'
        from /var/lib/gems/1.9.1/gems/activerecord-4.2.4/lib/active_record/persistence.rb:50:in `create!'
        from main.rb:55:in `<main>'

Aucun commentaire:

Enregistrer un commentaire