【问题标题】:Rails 4 - Time zone displayRails 4 - 时区显示
【发布时间】:2016-04-15 10:15:14
【问题描述】:

我正在尝试在 Rails 4 中制作应用程序。

我有一个地址模型、一个配置文件模型和一个用户模型。

地址是多态的。

这些关联是:

地址.rb

belongs_to :addressable, :polymorphic => true

个人资料.rb

belongs_to :user

  has_many :addresses, as: :addressable
    accepts_nested_attributes_for :addresses,  reject_if: :all_blank, allow_destroy: true

用户.rb

  has_one :profile, dependent: :destroy

在我的个人资料表单中,我要求用户添加他们的地址。地址表单字段包含一个用于存储用户时区的属性。

地址表单域文件有:

<div class="nested-fields">

  <div class="container-fluid">

                <div class="form-inputs">
                    <div class="row">
                <%=   f.country_select  :country, priority: [ "Australia", "New Zealand", "United Kingdom" ]  %>

                        </div>
              <div class="col-xs-3 col-xs-offset-1">
                <%= f.input :time_zone %>
              </div>

在我的配置文件显示文件中,我从我的配置文件视图文件夹中呈现了部分内容,该文件夹旨在显示时区中的时间。我试过了:

<% if @profile.addresses.any? %>

        <%= Time.now.in_time_zone(current_user.profile.time_zone) %>
    <% else %>
        <span class="profileeditlink">
            <%= link_to "Add your location" %>
        </span>

当我尝试此操作时,我在服务器日志中显示此错误:

ActionView::Template::Error (undefined method `time_zone' for #<Profile:0x007f97b35c0380>)

我可以填写个人资料表单中的地址表单字段并提交,但显示页面中的记录没有更新。如果我在控制台中设置时区,它会更新但不会显示。

当我在 google 中检查代码时,它只是一个空的 div 标签,中间有“...”。

谁能看到我做错了什么?

这篇文章似乎建议我在时区显示中使用的表达形式应该可以工作:

https://robots.thoughtbot.com/its-about-time-zones

我将这个私有方法添加到我的地址控制器中只是为了看看它是否有什么不同。它没有(至少为此目的)。虽然我不能说我明白这意味着什么。

  around_action :user_time_zone, :if => :current_user
def user_time_zone(&block)
  Time.use_zone(current_user.profile.time_zone, &block)
end

我在每个地址和配置文件控制器中都包含了 strong_params。我想不出还要检查什么来解决这个问题。

我的地址表有:

t.string   "time_zone"

【问题讨论】:

  • 哪个表中有time_zone 列?
  • 谢谢 - 你找到了。

标签: ruby-on-rails ruby time timezone


【解决方案1】:

我相信您会收到 undefined method `time_zone' 错误,因为您可能没有在迁移文件中定义字段 t.string :timezone

否则,如果您确实在迁移文件中定义了它,则运行 current_user.profile.methods 以查看 :time_zone 方法是否可见。

另外,请确保您的包括 &lt;%= form_for(@instance_variable) do |f| %&gt;&lt;%= f.submit %&gt; 在制作 rails 表单以确保正确提交数据时。

请参阅:Form forin time zone

祝你好运!

【讨论】:

  • 嗨,我的地址表中包含“time_zone”作为字符串。我在上面编辑了我的帖子以显示它。我正在使用带有 cocoon gem 的嵌套表单,因此 address_fields 部分的表单设置略有不同。
【解决方案2】:

我有时很笨。这行得通。

<%= Time.now.in_time_zone(current_user.profile.addresses.first.time_zone) %>

【讨论】:

    猜你喜欢
    • 2015-06-02
    • 2011-03-13
    • 2015-01-06
    • 2015-10-19
    • 2016-06-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多