A few notes when using rails active record

Tram Ho

Active record is a great library of rails for manipulating databases. However, in the use process, many situations that we do not understand why it can be like that. But obviously only you have the wrong code, but the code does not run wrong. Here are a few such cases that I have encountered. Maybe you already know the redundant, but also not superfluous.

1, Scope return nil

There is a simple scope as follows:

What do you think User.test_nil will return? nil? Of course not. Scope if nil is returned, then all records will be returned. Similar to User.all . But naturally you return nil do? Functions like find_by , find_by_#{attribute} will return nil if not found. In most cases, everything will work fine, but if you can’t find it, you’ll get it. Lesson learned: Do not use find_by in scope.

2, where nil

Sometimes I see some newbie rails code like this.

I’m really discouraged with something like this, It’s true that it still works fine during normal times, but what if it’s rank nil? Isn’t code a little more secure? If you don’t know, the comparison with true null in sql would be

Just simple fix into.

That is, the active record will automatically correct the query to be is null if needed. If really need to use net sql. Be sure to pay attention to the type of DBMS you use and consider sanitize if needed. If I have time, I will say more later.

3, includes (). Limit ()

Sometimes you will encounter this in paging. First, you code a simple paragraph to retrieve data, paging (by kaminari is still fine), show out. But you found code sticking n + 1 query because it needs some other information when showing. You fix it, simply, use includes. And this is where the problem arises. For example, for 2 models as below.

Then query

Just by thinking, you will think that it will give you 5 users and bring all those posts. But no, joins will create a new style table.

UsersPosts
User1Post1
User1Post2
User1Post3
User2Post4
User2Post5
User3Post6

So limit will only retrieve 2 users. And because the call starts from User, it only returns 2 users but you can’t understand why it is. Maybe you see it rarely but once you do not know why always, watching the new data forever. In addition, if the number of rows is small, it does not work, because then the active record will split into 2 sql statements, pluck id and then select by print with the second query so it will not be okay. Everything only comes out when it comes to products or somewhere that generates a lot of data.

Share the news now

Source : Viblo