Clear ruby ​​view logic and split problems into model / controller

I want to display a random assortment of 6 tools from my database on my home page. I created a Pages controller with a home action.

This is my page controller:

class PagesController < ApplicationController def home @tools = Tool.all end end 

Then, in my home.html.erb view, I use the .sample method to grab random tools from my database as such (repeat this 6 times using the variables tool1, tool2, tool3, etc. for each):

 <% tool1 = @tools.sample %> <%= image_tag tool1.tool_image.url(:medium) %> <%= tool1.name %> <%= tool1.description %> 

I am wondering if there is a better way to do this. It seems that I have a logic, in my opinion, and should there be a way to move this logic somewhere else? My model, controller, etc. How could you clear this code so that it performs well? Or maybe this is a good rails code, and I just don't know it since I start.

+2
source share
2 answers

The controller does not need to retrieve everything from tools_table , so I will remove .all first. In your example, it seems to you that you just need 6 random objects from the database, here is one way to do this:

 class PagesController < ApplicationController def home @tools = Tool.order("RANDOM()").first(6) end end 

Then, in your opinion, you can simply skip them:

 <% @tools.each do |tool| %> <%= image_tag tool.tool_image.url(:medium) %> <%= tool.name %> <%= tool.description %> <% end %> 
+5
source

In addition to Anthony's answer.

To clear the view using some rail magic, you can also add a partial link to your app/views/tools :

  _tool.html.erb 

Looking like:

  <%= image_tag tool.tool_image.url(:medium) %> <%= tool.name %> <%= tool.description %> 

And then change your view to

 <%= render @tools %> 

And Rails will know what to do if @tools is a toolbox 😄

+1
source

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


All Articles