Rails 4 ActiveRecord undefined method - ruby-on-rails-4

I’m trying to retrieve individual attributes from a record after retrieving it from the database. I get an error indicating an undefined method.
I retrieve the table here:
t = Table.where('##fil = ? ', r.referenced_object_ID)
I know I’m getting a record because I can list all the attributes in the record using:
t.to_json
and get this result:
[{"##fil":"1026.0","objtyp":"FIL","objatr":"CPT","fil":"Account”,…
However, when I try to use:
t.fil
I get
undefined method ‘fil’…

To directly get single record if fil is unique
t = Table.find_by_fil(r.referenced_object_ID)
If fil is not unique then use your approach then use
t.first.fill #to get first record
Or if you need all record use loop
t..each do |tbl|
tbl.fil
end

'where' clause always returns us an array. So in your case you can access it as
t.first.fil

Related

Add extra field and value to django query set

Hi I am doing a query like
user_list = Myuser.objects.filter(status=active)
now I want to add a new filed matching_percentage to a user who query it , Like want to show how much it matches to your profile. Now I searched annotate function but till now I found that you cant assign a custom calculated value to new filed .
So Is there any way to assign to a filed int values to show how much it matches my profile on run time by a algorithm ?
Update
I am trying something like this
query=MyUser.objects.annotate(annotated_field=Value(MyFunction(F('id')), output_field=IntegerField()))\
.filter(id__in=ids)
F('id') is not converting to ID just passing in function as a string

Django update model in shell not saving

I´m trying to update the data of an existing model with a csv. I read the file and assign the values with no problem.
If I try `MyModel.update() everything runs with no error but the data is not saved.
with open('Productosold.csv') as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
p = ProductosBase.objects.filter(codigo_barra = row['codigo_barra'])
p.region=row['region']
p.producto_ing=row['producto_ing']
p.packaging_ing=row['packaging_ing']
p.precio_compra=row['precio_compra']
p.uom=row['uom']
p.units_inner=row['units_inner']
p.inner_master=row['inner_master']
p.tier=row['tier']
p.precio_lista_internacional=row['precio_lista_internacional']
p.update()
I usualy upload new data using the MyModel.save() method and have no problem.
Now, if I use that I get "Queryset has no attribute save".
p.save()
If I print some of the p.values I can see they are populated correctly from the csv file.
What I´m doing wrong?
Thanks in advance!
.filter always returns a queryset, not a single instance. When you set all those values, you are just setting (previously non-existing) attributes onto that queryset object; you are not setting fields in a model instance. You should use .get to get an instance and save that.
p = ProductosBase.objects.get(codigo_barra = row['codigo_barra'])
p.region=row['region']
...
p.save()
However, since all the columns in your CSV map precisely to fields on the model, you could in fact use filter and update to do the whole thing in one go:
for row in reader:
ProductosBase.objects.filter(codigo_barra=row['codigo_barra']).update(**row)
and no need for any of the rest of the code.
You need filter() whenever you expect more than just one object that matches your criteria. If no item was found matching your criteria, filter() returns am empty queryset without throwing an error.
Also you can use get() but when you expect one (and only one) item that matches your criteria. Get throws an error if the item does not exist or if multiple items exist that match your criteria. You should therefore always use if in a try.. except .. block or with a shortcut function like get_object_or_404 in order to handle the exceptions properly. I'd recommend using get_object_or_404 in this case.
p = get_object_or_404(ProductosBase, codigo_barra=row['codigo_barra'])

how to use 'select limit 1' in rails 4.1

I want to use this code:
select id from categories where hotel_id=4 limit 1
I am new in rails. How do i use activerecord in controller to achieve the same result as the above code.
I already have hotel_id in params in my controller.
Try in your controller this:
#category = Category.where(:hotel_id => 4).limit(1)
OR
#category = Category.where(:hotel_id => 4)
It will return all the data from categories table which has hotel_id as 4
You can check it by write this line next to above code.
abort #category.inspect # to check in browser what does this object contains
If you want first data from the object then you can write #category.first same as for last entry #category.last after first line..
If you need only one first match record then you can use find_by
#category = Category.find_by(:hotel_id => 4)
The right answer would be using limit(1) reference
Using first or last actually runs the whole query then returns the first element only, would perform badly if the result set is large.
So just stick with limit
EDIT:
I just checked and i found that using first and last do actually add limit statement to the query, so I guess they are also just as correct as limit(1)
You can use .limit(1) or .first or .last
Model.where(hotel_id: 4).limit(1)

Django Nested Filter Values

This line works and returns the value that I'm looking for:
logs = Log.objects.filter(filterURI=aFilter.uri).values()[0]['yk']
However, when I try to add another filter and do the same I get errors:
logs = Log.objects.filter(filterURI=aFilter.uri).filter(k=k-1).values()[0]['yk']
My understanding is that a object.filter returns a queryset but so does a 'filter of a filter'. So I should be able to do the 'values' call in the same way regardless of whether I have one filter or 1000.
What am I doing wrong here.
Thanks in advance.
I don't think the error is in the fact that you have two filters - it's in the actual second filter. k=k-1 will only work if you have both a model field and a local variable called k - the first is on the left of the expression, the second on the right.
If you want to refer to the model field on the right of the expression, use F:
.filter(k=(F('k')-1)

Output location of images for django-imagekit

I'm trying to output a list of images that belong to each record in my app as below:
pri_photo = vehicle.images.all()[:1]
sec_photos = vehicle.images.all()[1:]
This first part is OK. The part I'm having issues with is when I try
pri_photo.original_image.url
sec_photos.original_image.url
The above two lines of code give me a 'QuerySet' object has no attribute 'original_image'. What could be the issue?
I also want the photos in sec_photos to be output as image1, image2,... upto the last one
[:1] just limits the number of records returned by the queryset, still it is a queryset result, not a single object.
to get a single object, you shoud use
[0]
or
[0:1].get()
but it's not safe, as it will raise an error if none objects match the query. to do it properly, use filter() and if result are present then get(), or
try:
#get()
except modelname.DoesNotExist:
# do shomething else
also, if you are looking for the latest object, maybe you can just use http://www.djangoproject.com/documentation/models/get_latest/