如何将我的布尔输出更改为ruby中的字符串值

Doi*_*gey 7 ruby ruby-on-rails

我有一个表单,我的用户输入一个人回复婚礼邀请.他们输入一个名称,菜单选项,然后选择:参加 - 是/否 - 然后我会用标签计算真假数量,这样用户就可以看到有多少人参加或不参加.

我的问题出在表格中.RSVP列所在的位置,我现在只是得到'真'或'假'.无论如何在Ruby中我可以将其更改为index.html.erb的字符串值吗?

指数

<% @replies.each do |reply| %>
  <tr>
    <td><%= reply.name %></td>
    <td><%= reply.menu %></td>
    <td><%= reply.rsvp %></td>
    <td><%= link_to 'Show', reply, class: "btn" %></td>
    <td><%= link_to 'Edit', edit_reply_path(reply), class: "btn" %></td>
    <td><%= link_to 'Delete', reply, method: :delete, data: { confirm: 'Are you sure?' }, class: "btn btn-danger" %></td>
    <td><%= reply.user.full_name %></td>
  </tr>
<% end %>
Run Code Online (Sandbox Code Playgroud)

reply.rb

class Reply < ActiveRecord::Base
  attr_accessible :menu, :name, :rsvp, :user_id
  belongs_to :user

  def self.find_attending
    Reply.where(:rsvp => "true").count
  end

  def self.find_not_attending
    Reply.where(:rsvp => "false").count
  end
end
Run Code Online (Sandbox Code Playgroud)

_form.html.erb

<%= f.input :user_id, collection: User.all, label_method: :full_name, :label => 'Added By' %>
<%= f.input :name, :label => 'Person(s) Name' %>
<%= f.input :menu, :label => 'Menu Choice' %>
<%= f.collection_radio_buttons :rsvp, [[true, 'Attending'] ,[false, 'Not Attending']], :first, :last %>
Run Code Online (Sandbox Code Playgroud)

D b

class CreateReplies < ActiveRecord::Migration
  def change
    create_table :replies do |t|
      t.string :name
      t.text :menu
      t.boolean :rsvp, :default => false

      t.timestamps
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

我对Ruby很新,任何指针都会受到赞赏.非常感谢.

小智 12

怎么样"#{reply.rsvp}"?似乎更干净,不是吗?


Chr*_*erg 8

只需使用三元:

reply.rsvp ? "true" : "false"
Run Code Online (Sandbox Code Playgroud)

用你想要显示的任何字符串替换"true"和"false".

  • 实际上,对于非布尔值的值,您也可以使用相同的技巧.例如,如果`reply.rsvp`的值为`nil`,它将在此上下文中评估为`false`,因此三元将计算为字符串`"false"`.不确定这是否有意义,但它是一个方便的技巧(一般用于红宝石条件,而不仅仅是三元组). (2认同)