【问题标题】:Rails: show post when attributes is set to trueRails:当属性设置为true时显示帖子
【发布时间】:2016-02-04 08:53:36
【问题描述】:

我正面临一个奇怪的错误,不幸的是我不知道如何调查它。

integer => pinoftheday 设置为 true 时,我会在我的主页上呈现某些图钉。我正在手动将一些引脚设置为 true。

对于某些 pin,它运行良好并且它们出现在主页上,而另一些则没有。顺便说一句,我正在检查我的控制台,它们已正确设置为 true。

这是一段代码:

  <% @pins.each do |pin| %>
    <% if pin.pinoftheday %>
          (...) some informations about the pin 
    <% end %>
  <% end %>

有什么想法可以检查为什么某些引脚没有呈现吗?我现在不写任何测试......我知道这很愚蠢,但我只是没有学习过 Rails 测试。

谢谢。

编辑:是的,在我的代码中它是一个引脚模型。我想用帖子让它更清楚。认为它不是:) - 将其编辑为正确的模型:pin。

【问题讨论】:

  • 这里有什么帖子?还是应该是 pin ? (...) 一些关于 pin 的信息
  • 在你的代码中@postss应该是@posts,顺便说一句post有错字,应该是pin,对吧?

标签: ruby-on-rails integer rendering


【解决方案1】:

试试下面的代码。

 <% @postss.each do |post| %>
    <% if post.pinoftheday %>
          (...) some informations about the pin 
    <% end %>
  <% end %>

【讨论】:

    【解决方案2】:

    您的问题是您在块中定义了local variable,并且正在引用另一个:

    <% @postss.each do |post| %>
      <% if post.pinoftheday %>
          ...
      <% end %>
    <% end %>
    

    --

    你最好使用scope

    #app/models/post.rb
    class Post < ActiveRecord::Base
       scope :pin_of_the_day, -> { where pinoftheday: true }
    end
    

    您还可以将pinoftheday 列设为boolean。如果您引用1 = true; 0 = false,Rails 会在您的数据库中使用tinyint 处理它,并将true/false 作为布尔逻辑调用。您可以调用 true 等来代替将整数引用为数字。

    以上将允许您调用:

    #app/controllers/your_controller.rb
    class YourController < ApplicationController
       def index
         @postss = Post.pin_of_the_day
       end
    end
    

    这将删除低效的条件逻辑(&lt;% if ...):

    <% @postss.each do |post| %>
       ...
    <% end %>
    

    【讨论】:

    • 是的,感谢 Rich 的投入。你是对的,使用范围并从控制器调用 pinoftheday 是一种更清洁的方法。关于布尔值的使用,我不确定,我一直读到它会减慢应用程序的速度。
    【解决方案3】:

    如果我理解了你的代码,那么会在下面:

    <% @postss.each do |pin| %>
      <% if pin.pinoftheday.nil? %>
          (...) some informations about the pin 
       <% else %>
          (...) some informations about the pin 
      <% end %>
    <% end %>
    

    希望能帮到你

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-09-01
      • 2021-03-08
      • 1970-01-01
      • 2011-09-03
      • 1970-01-01
      • 2018-01-15
      • 2023-03-27
      • 2017-01-02
      相关资源
      最近更新 更多