Harakiri
Harakiri

Reputation: 730

Rails console: Update attributes and save to DB

I want to update existing records in the rails console.

Order.all.each do |tname| tname.team = User.where(:id => tname.user_id).pluck(:team).shift end

Is working but the result is not getting saved to the DB.

Both

Order.all.each do |tname| tname.team = User.where(:id => tname.user_id).pluck(:team).shift self.update_columns(team: tname.team) end

Or

Order.all.each do |tname| tname.team = User.where(:id => tname.user_id).pluck(:team).shift self.update_attributes(team: tname.team) end

Are not working. (NoMethodError: undefined method `update_attributes' for main:Object)

Any Ideas? Thanks in advance!

Edit (schema):

create_table "users", force: :cascade do |t|
 t.text     "team"
end

create_table "orders", force: :cascade do |t|
 t.integer  "user_id"
 t.string   "team"
end

Upvotes: 0

Views: 1983

Answers (2)

Harakiri
Harakiri

Reputation: 730

Strange fix:

By typing it in 2 steps that works:

1) Order.all.each do |tname| tname.team = User.where(:id => tname.user_id).pluck(:team).shift

2) tname.save end

Instead of

Order.all.each do |tname| tname.team = User.where(:id => tname.user_id).pluck(:team).shift tname.save end.

Absolutely no clue why..

Upvotes: 0

davegson
davegson

Reputation: 8331

What you are doing is highly inefficient:

Order.all.each do |tname|
  tname.team = User.where(:id => tname.user_id).pluck(:team).shift
end

You hit the database with every order, resulting in many queries. Also, selecting the team via pluck is... wierd. If you want to get a User and access its team use:

User.find_by(id: tname.user_id).team

But you should do this in one query anyway. If you set up the relations correctly, this should do the job:

Order.joins(:user).update_all('team = users.team')

Upvotes: 1

Related Questions