Cleaning up view ruby logic and separating concerns into model/controller

笑着哭i 提交于 2019-12-11 02:38:39

问题


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.


回答1:


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 %>



回答2:


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 😄



来源:https://stackoverflow.com/questions/29724991/cleaning-up-view-ruby-logic-and-separating-concerns-into-model-controller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!