开发者

how to add data to database from rails console

I have a User model.

>> @u = User.new
=> #<User id: nil, userid: nil, password: nil, created_at: nil, updated_at: nil, user_first_name: nil, user_last_name: nil, user_status: nil, user_type: nil>

I am not able to add data to the Users table from the console. I am doing the following:

>> @u.userid="test1"
=> "test1"
&开发者_如何学编程gt;> @u.password="test2"
=> "test2"
>> @u.user_first_name="test3"
=> "test3"
>> @u.user_last_name="test4"
=> "test4"
>> @u.user_status="test5"
=> "test5"
>> @u.user_type="test6"
=> "test6"
>> @u.save
NoMethodError: undefined method `userid' for nil:NilClass

what am i doing wrong? I just simply want to add one row of data to the app.


>> u = User.create :userid => "myuserid", :password => "mypasswd", :user_first_name => "test", :user_last_name => "testovich", :user_status => "mystatus", :user_type => "mytype"


Try checking to see if the instance you create is valid. The easiest way is to use the save! method...

@u.save!

This will cause an exception to be raised if the instance doesn't pass all validations, or if any other issues are found. The stack trace will then hopefully provide some useful info.

Also, instead of using @u = ... trying using just u = ...


I have tried to create a new rails app, and I can do the following:

irb(main):008:0> u= User.new
=> #<User id: nil, name: nil, created_at: nil, updated_at: nil>
irb(main):009:0> u.save
=> true
irb(main):011:0> User.find(3)
=> #<User id: 3, name: nil, created_at: "2010-03-22 11:51:31", updated_at: "2010-03-22 11:51:31">

The same works with create instead of new. I suppose that your model of User wants to have relation to another object which is not available yet. Could you provide your current scheme (located in db/schema.rb)?

Mine is looking like that:

ActiveRecord::Schema.define(:version => 20100322114826) do

  create_table "users", :force => true do |t|
    t.string   "name"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

end


u = User.new(:userid => "myuserid", :password => "mypasswd", :user_first_name => "test", :user_last_name => "testovich", :user_status => "mystatus", :user_type => "mytype")
u.save

Simply by these 2 lines you can add data to your database.


You can enter this right from rails console: User.create(:userid => "myuserid", :password => "mypasswd", :user_first_name => "test", :user_last_name => "testovich", :user_status => "mystatus", :user_type => "mytype")

I always like to run: .new so I can an exact list of what parameters I'm looking to add values to. Also not all the values need to be listed or filled out i.e. User.create(:userid => "myuserid", :password => "mypasswd") all other values will have a nil value. Hope this helps.


One-liner

User.create name: "Mr X", color: "#f20075"


You can also use

@u.valid?

in order to check if your instance is valid and don't want to risk adding bad data to your database.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜