Rails 5 - 将db中的整数转换为写出的月份

时间:2017-08-08 18:42:09

标签: ruby-on-rails ruby ruby-on-rails-5

我有一块红宝石代码,我在我的视图中打印了month_published列。

<?php

require('dbConnect.php');

//this is the username in the user table
$Number = "+353872934480";

// get the username of the user in the user table, then get the matching user_id in the user table
                // so we can check contacts against it 
                $query = "SELECT * FROM user WHERE username = ?";
                $stmt = $con->prepare($query) or die(mysqli_error($con));
                $stmt->bind_param('s', $Number) or die ("MySQLi-stmt binding failed ".$stmt->error);
                $stmt->execute() or die ("MySQLi-stmt execute failed ".$stmt->error);
                $result = $stmt->get_result();

            while ($row = $result->fetch_assoc()) {

            //this is the corresponding user_id in the user table of the user
            $user_id = $row["user_id"];
            }

//post all contacts for user_id as a JSON array
$phonenumberofcontact ='["+11111","+222222","12345","67890","123456","78901","234567","8901234"]';
$array = json_decode($phonenumberofcontact);

//We want to check if contacts of user_id are also users of the app. 
 $query = "SELECT * FROM user WHERE username = ?";
 $stmt2 = $con->prepare($query) or die(mysqli_error($con));
 $stmt2->bind_param('s', $phonenumberofcontact) or die ("MySQLi-stmt binding failed ".$stmt->error);

 //for each value, call it $phonenumberofcontact
    foreach ($array as $value)
    {
                $phonenumberofcontact = $value;

$stmt2->execute() or die ("MySQLi-stmt execute failed ".$stmt2->error);

//match the phone numbers in the JSON Array against those in the user table
     $result2 = $stmt2->get_result(); 
            //make an array called $results
            //this is a matching number in user table and in the JSON Array
            //call this username contact_phonenumber
$results = array();
while ($row = $result2->fetch_assoc()) {
    $results[] = array('contact_phonenumber' => $row['username']);//remove extra ,
}
$json2 = json_encode($results);
echo $json2;

    }

        ?>

所有这些值都存储为整数:01表示1月,02表示2月等,因此它打印的是什么。 如何让我的代码将单词写成单词而不是整数?

3 个答案:

答案 0 :(得分:1)

您也可以使用I18n来完成此任务:

I18n.t('date.month_names')[01]

这应该是en的开箱即用,但如果您需要其他语言,则需要添加

fr:
  date:
    month_names:
    -
    - janvier
    - février
    - mars
    - avril
    - mai
    - juin
    - juillet
    - août
    - septembre
    - octobre
    - novembre
    - décembre

作为您的语言环境文件的示例(从local/fr.yml项目的rails-i18n快速抓取的翻译)

答案 1 :(得分:0)

您可以使用常量Date::MONTHNAMES,它由Rails定义,如下所示:

[nil, "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]

所以在你看来你必须做这样的事情:

<% @publications.each do |publication| %>
    <p><%= Date::MONTHNAMES[publication.month_published] %></p>
<% end %>

答案 2 :(得分:0)

实现这一目标的一种方法是使用

(%B)

在你的情况下,

strftime

应该运作良好。

$images_dir参数转换为完整的月份名称。有关可与$thumbs_dir一起使用的其他指令,请参阅THIS链接。