【问题标题】:Rails Output of Boolean Value is Incorrect布尔值的 Rails 输出不正确
【发布时间】:2016-11-28 07:42:14
【问题描述】:

背景

我的 rails 应用中有一个故事模型。模型的一部分是“已发布”的布尔值。

在创建和编辑表单上,我有一个切换按钮,如果故事已发布,则显示“打开”,如果故事未发布,则显示“关闭”。此切换当前工作正常,我可以切换故事的发布或不发布;;这个切换会相应地更新数据库。

问题

在显示页面上,我试图做一个 if 语句,但它没有正确解析,所以我只是打印了已发布的变量,即使检查设置的数据库,它也总是打印出“false”为“真”。

守则

<% @title="Stories" %>

<p><strong><%= @story.heading %></strong></p>

<p><%= @story.body %></p>

<p>
  <%= #!!!!!!!!!!!!!!!!Not working currently!!!!!!!!!!!!!
      # if @story.published 
      #   @publish_Notice = "This story has been made public."  
      # else
      #   @publish_Notice = "This story is private."  
      # end
      # @publish_Notice 

      @story.published   # Always prints out 'false' even when database shows 'true'
  %>
</p>

<p>~ <%= @story.authorName %></p>

<p>Submitted: <%= @story.created_at.strftime("%B, %d %Y") %><br/>

<%=
  @location = " "

  if @story.locationCity == "" || @story.locationCity == " " || @story.locationCity.nil?
    @location = " "
  else
    @location = "Near: " @story.locationCity + ", " + @story.locationState 
  end
%>
<%= @location %></p>

<% if (user_signed_in?) && (current_user == @story.user) %>
  <%= link_to 'Edit', edit_story_path(@story) %> |
  <%= link_to 'Delete', @story, method: :delete, data: { confirm: 'Are you sure?' } %> | 
<% end %>
<%= link_to 'Back', stories_path %>

【问题讨论】:

  • 您在哪一行遇到问题?
  • @uzaif,我在打印已发布信息的行中遇到了问题。我的代码中有 cmets 显示问题所在。

标签: ruby-on-rails ruby database sqlite boolean


【解决方案1】:

答案 经过 2 天自己试图找出并解决这个问题,但没有提出任何问题并最终在此处发布问题后,几分钟后,我在我的故事控制器中的代码 sn-p 中发现了问题。看看您是否可以在下面的代码中找到问题。

旧代码

def show
  if @story.published = false && @story.user != current_user
    redirect_to stories_url, notice: 'That action is not permitted.'
  end
end

说明

我设置了这个代码 sn-p 来阻止人们在浏览器中输入故事编号并看到它,即使它没有发布。问题代码在我检查故事是否已发布的第二行。我只放了一个等号,因此每次显示一个故事时,它都会将已发布的变量更改为“假”,而无需更改数据库。我添加了额外的等号,现在一切正常。这是新代码。

新代码

def show
  if @story.published == false && @story.user != current_user
    redirect_to stories_url, notice: 'That action is not permitted.'
  end
end

感谢那些如此迅速地询问后续信息以帮助我解决问题的人。感谢您的帮助。

【讨论】:

  • 错过一个=会带来很多麻烦。
  • if @story.published &amp;&amp; ... 可能会更好地为您服务。或者甚至可能是if @story.visible_to(current_user),在visible_to 方法中隐藏了所有“它是否已发布”和“这个人是作者”的逻辑。
  • 总是不建议使用x == false!您可能会遇到以下问题:该方法返回nil,它也将被解释为false。所以为了将来,只使用if x
猜你喜欢
  • 1970-01-01
  • 2016-01-16
  • 2022-10-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-11
  • 2018-01-22
  • 1970-01-01
相关资源
最近更新 更多