Cleaning up view ruby logic and separating concern

2019-07-20 08:08发布

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.

2条回答
闹够了就滚
2楼-- · 2019-07-20 08:45

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:

  _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 collection of tools

查看更多
贪生不怕死
3楼-- · 2019-07-20 08:48

Your 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:

class PagesController < ApplicationController

    def home
        @tools = Tool.order("RANDOM()").first(6)
    end

end

Then in your view you can just loop through those:

<% @tools.each do |tool| %>
  <%= image_tag tool.tool_image.url(:medium) %>
  <%= tool.name %>
  <%= tool.description %>
<% end %>
查看更多
登录 后发表回答