0

I have two tables, Beacon belongs to Category and Category has many beacons, in beacon table, I add a foreign key: category_id, but when i want display in table, i need the category_name in the category table, now I use a stupid way as following:

...
<% @beacons.each do |beacon| %>
            <tr>
              <td><%= beacon.beacon_uuid %></td>
              <% @category_name = Category.find(beacon.category_id).category_name %>
              <td><%= @category_name %></td>
...

but when beacon data get bigger, request get bigger, how to change my code to defence this stupid question?can someone give me some suggestion or reference? Thanks a lot.

2 Answers 2

2

It sounds like you're referring to an N+1 query, wherein the number of queries executed is equal to the number of beacons + 1. If so, your queries look similar those below.

select beacons.* from beacons;
select categories.* from categories where categories.id = 1;
select categories.* from categories where categories.id = 2;
select categories.* from categories where categories.id = 3;

Assuming your beacon model has the belongs_to :category relation declared, this can be avoided by using includes to eager load the association in the controller

def index
  @beacons = Beacon.all.includes(:category)
end

The view can then be changed to take advantage of this, instead of pulling a fresh copy of the category from the database for each beacon

<%= beacon.category.category_name %>
Sign up to request clarification or add additional context in comments.

Comments

0

There is a helper of the category and its attributes in the beacon itself.

In Rails, you can go both ways:

Category.beacons will return an array of all the beacons the category has and their attributes Beacon.category will return the attributes of its category.

Following the same logic, you just need this:

  <%= beacon.category.category_name %>

1 Comment

Thanks...I tried, but in this case, when I have 10 beacon, it's still send 10 request to get category_name, this way is more clearly than before, but do the same thing... can I use only 1 request to get what I want?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.