清理视图红宝石逻辑并将关注点分离到模型/控制器中 [英] Cleaning up view ruby logic and separating concerns into model/controller

查看:77
本文介绍了清理视图红宝石逻辑并将关注点分离到模型/控制器中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在我的主页上从数据库中随机显示6种工具.我用主页操作创建了一个Pages控制器.

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.

这是我的Pages控制器:

This is my Pages controller:

class PagesController < ApplicationController

    def home
        @tools = Tool.all
    end

end

然后在home.html.erb视图中,我使用.sample方法从数据库中随机获取工具(我分别使用tool1,tool2,tool3等变量重复了6次):

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

我想知道是否有更好的方法可以做到这一点.看来我有逻辑,必须找到一种将逻辑移到其他地方的方法吗?我的模型,控制器等.如何清理此代码,使其成为好的Rails代码?也许这是很好的Rails代码,但由于我是初学者,所以我只是不知道.

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.

推荐答案

您的控制器不需要从tools_table中提取所有内容,因此我首先要删除.all.您的示例使您似乎只需要从数据库中获取6个随机对象,这是一种实现方法:

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

这篇关于清理视图红宝石逻辑并将关注点分离到模型/控制器中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆