简体   繁体   中英

Edit a database record through the Rails console

Example scenario: I'm on my mac's Terminal inside the Rails console and have just entered the following database record with a misspelling in one of the fields:

irb(main):019:0> Meme.create(:category => 'funny', :title => 'Balloon frihgtens cat')

Q: Using the Rails console, how can I fix that record to have the correct spelling of "frihgtens"?

Step 1. Find the record.

Step 2. Edit the record.

Assuming title is unique, the following should work:

> m = Meme.where(:title => 'Balloon frihgtens cat').first
> m.title = 'Balloon frightens cat'
> m.save

Read up http://guides.rubyonrails.org/active_record_querying.html to learn more about using active record.

Type the following inside rails console not irb

meme = Meme.find_by(:title => 'Balloon frihgtens cat')
meme.title = 'Ballon frightens cat'
meme.save

Cheers

Client.find(3).update(key: "value")

Client ---> table,
find(3) ---> which record,
key ---> which column,
value ---> what changes u want to update

  • Find the record

    You can use find or where to get the record open up the rails console run the command Meme.all spot the record you want to update, get the ID of that record.(Lets say ID is 5)

    @meme = Meme.find(5) or @meme = Meme.where(:title => "Balloon frihgtens cat")

  • Update the record

    @meme.update(:title => "Balloon frightens cat")

please try to following code:

meme = Meme.where(:title => 'Balloon frihgtens cat').first
meme.update_attribute(:title, 'Balloon frightens cat')

you need to do 3 things: 1 Find the record:

x = Record.where(title: "whatever")

Update it:

x.title = "new title"

Save it:

x.save

And do not use irb use rails console.

You can use this oneliner:

Company.update 1, name: 'Rebranded', score: 99

where first parameter is id.

You are using irb , not rails console .

AppledeMac-mini-2% rails c Loading development environment (Rails 4.2.1) 2.1.6 :001 >

A: If something wrong, you will get a error report. But this can not check the spiling of the value. Like this: 2.1.6 :003 > Menu.create(naame: 'aa') ActiveRecord::UnknownAttributeError: unknown attribute 'naame' for Menu.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM