How to assign values for update_attributes in rails? - ruby

I have a noob question about assigning values using update_attributes.
In the exam controller, a new exam record is saved and then an patient record is retrieved which matches some of the new exam fields. This part works fine.
#exam.save
#patient = Patient.joins(:charts).where(:dob => #exam.patient_dob).where(:charts => { :provider_id => #exam.provider_id, :patient_mrn => #exam.patient_mrn })
Then i try to update the new #exam record with a value from the #patient record using the following which crashes and burns......
#exam.update_attributes(:patient_id, #patient.id)
How have i gone so far astray?

You're updating a single value there, not multiple values, so update_attribute would be more appropriate. update_attributes takes a hash of values to update.
See http://apidock.com/rails/ActiveRecord/Base/update_attribute and http://apidock.com/rails/ActiveRecord/Persistence/update_attributes

Related

UpdateOrCreate not working has expected

im trying to user the method "updateOrCreate", and works almost has expected but with a problem.
For example if the record doesnt exists it creates, untill now great, but for example if i change a value in my case the "mybankroll" value it creates another record. I can that understand that is creating because one of the columns record value doesnt exist, but i dont understand how the update actions is fired.
My code example:
UserBankroll::updateOrCreate(
['my_bankroll' => $request->mybankroll, 'currency' => 'EUR'],
['user_id' => Auth::user()->id]
);
But if i try to update the value of my_bankroll, instead of updating it created another record.
You seem to have your arrays backwards.
The first array should be what you are matching against, the second array should be the update values.
https://laravel.com/api/5.0/Illuminate/Database/Eloquent/Model.html#method_updateOrCreate
UserBankroll::updateOrCreate(
['user_id' => Auth::user()->id],
['my_bankroll' => $request->mybankroll, 'currency' => 'EUR']
);

Laravel Create Record and Use ID Value in Another Column

When I create a new record in my Fan model, at the same time that I create the new Fan record, I want to use the new ID value in another column. I'm trying to do this all at once and not have another method to go back and update the record.
$fan = Fan::create([
'display_name' => $displayName,
'bio' => $bio,
'logo_url' => $logoUrl,
'algolia_id' => 'fan_'??, // I want to replace ?? with this record's ID value.
]);
I've tried $fan, but doesn't work since that variable isn't created yet. I cannot use Auth because the ID isn't the Auth user's ID.
Thanks!
I doubt you can automatically do it, you should do it in 2 steps:
$fan = Fan::create([
'display_name' => $displayName,
'bio' => $bio,
'logo_url' => $logoUrl
]);
$fan->algolia_id = 'fan_' + $fan->id;
$fan->save();
That said, it's not a great database design, you'd rather want to build the algolia_id field when you need to use it, since you'd store duplicated value (the id and the algolia_id are the same except for fan_).

Select distinct value from a list in linq to entity

There is a table, it is a poco entity generated by entity framework.
class Log
{
int DoneByEmpId;
string DoneByEmpName
}
I am retrieving a list from the data base. I want distinct values based on donebyempid and order by those values empname.
I have tried lot of ways to do it but it is not working
var lstLogUsers = (context.Logs.GroupBy(logList => logList.DoneByEmpId).Select(item => item.First())).ToList(); // it gives error
this one get all the user.
var lstLogUsers = context.Logs.ToList().OrderBy(logList => logList.DoneByEmpName).Distinct();
Can any one suggest how to achieve this.
Can I just point out that you probably have a problem with your data model here? I would imagine you should just have DoneByEmpId here, and a separate table Employee which has EmpId and Name.
I think this is why you are needing to use Distinct/GroupBy (which doesn't really work for this scenario, as you are finding).
I'm not near a compiler, so i can't test it, but...
Use the other version of Distinct(), the one that takes an IEqualityComparer<TSource> argument, and then use OrderBy().
See here for example.

Sequel Migration update with a row's ID

How can you run a Sequel migration that updates a newly added column with a value from the row?
The Sequel documentation shows how you can update the column with a static value:
self[:artists].update(:location=>'Sacramento')
What I need to do is update the new column with the value of the ID column:
something like:
self[:artists].each |artist| do
artist.update(:location => artist[:id])
end
But the above doesn't work and I have been unable to figure out how to get it to go.
Thanks!
artist in your loop is a Hash, so you are calling Hash#update, which just updates the Hash instance, it doesn't modify the database. That's why your loop doesn't appear to do anything.
I could explain how to make the loop work (using all instead of each and updating a dataset restricted to the matching primary key value), but since you are just assigning the value of one column to the value of another column for all rows, you can just do:
self[:artists].update(:location=>:id)
if you need update all rows of a table, because it is a new column that need be populate
artists = DB[:artists]
artists.update(:column_name => 'new value')
or if you need, update only a unique row into your migration file you can:
artists = DB[:artists]
artists.where(:id => 1).update(:column_name1 => 'new value1', :column_name2 => "other")

DataMapper first_or_create always set certain field?

I'm using the following with datamapper to create/get a new user from my db:
user = User.first_or_create({:id => data['id']})
This gets the user with id = data['id'] or creates it if it doesn't already exist.
I want to know how to set other attributes/fields of the returned object regardless of whether it is a new record or existing?
Is the only way to do this to then call user.update({:field => value ...}) or is there a better way to achieve this?
Well, you could write it as one line:
(User.first_or_create(:id => data['id'])).update(:field => value)
with hashes for the parameters if you wish (or if you need to specify more than one); however, it's worth noting that this will only work if the model as specified by the first_or_create is valid. If :name were a required field, for instance, then this wouldn't work:
(User.first_or_create({:id => data['id'], :name => "Morse"})).update(:name => "Lewis")
as the creation in the first part would fail.
You could get around this by specifying the parameters needed for a new record with something like
(User.first_or_create({:id => data['id'], :name => "Morse"}, {:name => "Lewis"})).update(:name => "Lewis")
but this is unusually painful, and is difficult to read.
Also note that using first_or_create with an :id will attempt to create a model with that specific :id, if such a record doesn't exist. This might not be what you want.
Alternatively, you can use first_or_new. You can't call update on an object created using this, however, as the record won't exist (although I believe this might have worked in previous versions of DataMapper).
Just for anyone coming across this answer, User.first_or_create({:id => data['id']}) does NOT "get the user with id = data['id'] or creates it if it doesn't already exist." It actually gets the first record in the table and changes its id t0 data['id'].
To actually get the first record with that id, or create it if it doesn't exist, you need to use a where clause:
User.where(id: data['id]).first_or_create

Resources