Ask A Question

Notifications

You’re not receiving notifications from this thread.

Rails console hacks :)

Sascha M. asked in Rails

Hi there,

I need some help how to handle the rails console commands. I'm really stuck here..

I've recently added a new column (teams) to my Sales and Orders model. Both models containing the user_id from the User model.
The column team already exists in the User model. So I want to do this:

Fill the team names in the Sales and Orders model through the user_id from the User model and pull the team name from there.

Something like (pseudo sql): insert team into Sale.team from User where user_id == Sale.user_id

I hope you get what I mean :)

Reply

Hi,

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

If I type this into the console the records get filled but not saved. What should I have to add to save the records?

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 both not working.

>> NoMethodError: undefined method `update_attributes' for main:Object

Any ideas?

Reply

Hey Sascha, I'd write it like this:

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

The problem is when you use self it doesn't point to the tname object, causing that issue.

Reply
Join the discussion
Create an account Log in

Want to stay up-to-date with Ruby on Rails?

Join 81,842+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.

    Screencast tutorials to help you learn Ruby on Rails, Javascript, Hotwire, Turbo, Stimulus.js, PostgreSQL, MySQL, Ubuntu, and more.

    © 2024 GoRails, LLC. All rights reserved.