Rails:当属性设置为 true 时显示 post

Rails: show post when attributes is set to true

我遇到了一个奇怪的错误,不幸的是我不知道如何调查它。

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

有些 Pin 图效果很好,它们出现在主页上,有些则没有。顺便说一句,我正在检查我的控制台,它们已正确设置为 true。

这里有一些代码:

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

有什么办法可以检查为什么有些图钉没有呈现吗?我现在不写任何测试...我知道这很愚蠢,但我只是没有学会 rails.

的测试

谢谢。

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

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

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

希望能帮到你

试试下面的代码。

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

你的问题是你在你的块中定义了一个 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

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

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