In Rails, after using find with: select, my objects are not saved

Running something like:

@users = User.find (: first ,: select => "first name, last name, salary") for @user in @users do @ user.salary = 100000 @ user.save end

After that, users are not updated in the Mysql table.

+3
source share
5 answers

ActiveRecord does not know the identifier of the object to save data. Therefore, include the id field in: select, as shown below:

@users = User.find (: first ,: select => "id, name, lastname, pay")

+18
source

, .
, : select. , . vars (@). @user var. @users, :

@users = User.find(:all, :select => "id, name, lastname, salary")
@users.each do |user|
  user.salary = 10000
  user.save
end

ActiveRecord update_all . , .

+2

.update .update_attributes: ( .save, )

0

Using .save! will also throw an error if it does not save.

0
source

I understand that this is a rather old question at the moment, but the correct answer, I believe that any objects returned by: select, are read-only.

See the official Rails guide for Active Record queries, section 3.2:
http://guides.rubyonrails.org/active_record_querying.html

Curiously, I do not see this documented in the API.

0
source

Source: https://habr.com/ru/post/1697070/


All Articles