I want to display a random assortment of 6 tools from my database on my home page. I have created a Pages controller with a home action.
This is my Pages 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(I repeat this 6 times using tool1, tool2, tool3, etc variables 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 logic in my view and there must be a way to move that logic somewhere else? My model, controller, etc. How would one go about cleaning this code up so that it's good rails code? Or maybe this is good rails code and I just don't know it since I am a beginner.
In addition to Anthony's answer.
To clear up the view with some rails magic you can also add a partial to your
app/views/tools
called:Looking like:
And then change your view to
And Rails will know what to do if
@tools
is a collection of toolsYour controller doesn't need to extract everything from the
tools_table
, so I'd first remove the.all
. Your example makes it seem like you just need 6 random objects from the database, here's one way to do that:Then in your view you can just loop through those: